input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
node-fetch receives empty body <p>I'm writing unit-tests for a simple NodeJS application and for some reason I cannot retrieve response body. It gets proper response code (either 200 for successful requests or 422 for invalid ones) but body appears to be empty. Also, when I'm making exactly the same request with <strong>httpie</strong> it works like charm. Logging also shows that controller works as expected.</p>
<p>Any ideas or suggestions are welcome.</p>
<p><strong>Here's the controller part:</strong></p>
<pre><code>function register (req, res) {
return _findUser({email: req.body.email})
.then(user => {
if (user) {
console.log('EMAIL TAKEN');
return Promise.reject({message: 'This email is already taken'});
}
let params = _filterParams(req.body);
if (_isRegistrationValid(params)) {
console.log('REGISTRATION VALID');
return params;
} else {
console.log('PARAMS INVALID');
return Promise.reject({message: 'Params invalid'});
}
})
.then(_createUser)
.then(_generateToken)
.then(token => {
console.log('SENDING TOKEN');
console.log(token);
res.send({token: token});
})
.catch(error => {
console.log('CATCH ERROR');
res.status(422).send(error);
});
}
</code></pre>
<p><strong>Here's the test section:</strong></p>
<pre><code>it ('Returns token when data is valid', done => {
fetch(`http://localhost:${testPort}/api/register`, {
headers: {'Content-Type': 'application/json'},
method: 'POST',
body: JSON.stringify({email: 'test@test.com', password: 'password', confirmPassword: 'password'})
})
.then(response => {
assert(response.ok); // this part works ok
expect(response.body.token).to.exist; // this part fails
done();
})
.catch(done);
});
</code></pre>
<p>Here's the <strong>httpie</strong> output:</p>
<pre><code>kpr$ http post localhost:4000/api/register email="rest@test.com" password="password" confirmPassword="password"
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 941
Content-Type: application/json; charset=utf-8
Date: Sat, 08 Oct 2016 11:39:30 GMT
ETag: W/"3ad-uBdW+HLbY7L2gb65Y+zptQ"
X-Powered-By: Express
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9_long_token_string_2M"
}
</code></pre>
<p><strong>Here's the test output:</strong></p>
<pre><code>REGISTRATION VALID
_createUser
(node:70495) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
_generateToken
SENDING TOKEN
eyJhbGciOiJIU_long_token_string_lmYA
0 passing (160ms)
2 pending
1 failing
1) Authorization Registration Returns token when data is valid:
AssertionError: expected undefined to exist
at fetch.then.response (test/auth-controller-spec.js:57:41)
at process._tickCallback (internal/process/next_tick.js:103:7)
</code></pre>
<p>Printing out response body from within <strong>fetch()</strong> shows some huge object:</p>
<pre><code>PassThrough {
_readableState:
ReadableState {etc...}
}
</code></pre>
| <p>You need to try <code>response.json()</code> instead of <code>response.ok</code> which will return the response in a proper way in your case.</p>
<p>Hope this helps!</p>
|
VueJS data() not working <p>I am trying to make a VueJS app but I am failing even with the simplest examples.
I am using Laravel 5.3 with pre-built support for VueJS (version 1, I tried version 2 as well).</p>
<p>Here is my Example.vue component</p>
<pre><code><template>
<div class="profile">
{{ name }}
</div>
</template>
<script>
export default {
data () {
return {
name: 'John Doe'
}
}
}
</script>
</code></pre>
<p>And here is the main code</p>
<pre><code>Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
el: '#app'
});
</code></pre>
<p>This is the error that shows up everytime in console:</p>
<p><em>[Vue warn]: Property or method "name" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in component )</em></p>
<p>Any ideas whats wrong?
Thanks</p>
| <p>Call the component inside your template</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.component('example', {
template: `<div class="profile">{{ name }}</div>`,
data () {
return {
name: 'John Doe'
}
}
})
const app = new Vue({
el: '#app'
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app"><example></example></div></code></pre>
</div>
</div>
</p>
|
Global variables code confusion <p>I am having trouble getting data input from one class to another and I cant seem to get the global function to work. The part i need help with is in the last function but it only works if you have the whole code.</p>
<pre><code>import tkinter as tk
import os
self = tk
TITLE_FONT = ("AmericanTypewriter", 18, "bold")
#exit function
def Exit():
os._exit(0)
#Functions end
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (Home, Population, Survival, Birth,NEW, data, Quit):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("Home")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class Home(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Home", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Population",
command=lambda: controller.show_frame("Population"))
button5 = tk.Button(self, text = "Quit",
command=lambda: controller.show_frame("Quit"))
button1.pack()
button5.pack()
class Population(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Enter Generation 0 Values", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
#Function
def EnterPopulation():
b1 = populationa.get()
print (str(populationa.get()))
bj = populationj.get()
print (str(populationj.get()))
bs = populations.get()
print (str(populations.get()))
def cal(*args):
total = population_juveniles + population_adults + population_seniles
#Population
population = tk.Label(self, text="Value for the Populations")
population.pack()
labela= tk.Label(self, text= 'Population of Adults')
populationa = tk.Entry(self)
labela.pack()
populationa.pack()
population3 = tk.Button(self, text="Enter", command = EnterPopulation)
population3.pack()
labelj= tk.Label(self, text= 'Population of Juvenile')
populationj = tk.Entry(self)
labelj.pack()
populationj.pack()
population5 = tk.Button(self, text="Enter", command = EnterPopulation)
population5.pack()
labels= tk.Label(self, text= 'Population of Seniles')
populations = tk.Entry(self)
labels.pack()
populations.pack()
population6 = tk.Button(self, text="Enter", command = EnterPopulation)
population6.pack()
buttonS = tk.Button(self, text = "Survival Rates",
command=lambda: controller.show_frame("Survival"))
buttonS.pack()
class Survival(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Survival Rates", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
def EnterSurvival(*self):
S = survivalaa.get()
ss = survivalj.get()
sss =survivals.get()
print(str(survivalaa.get()))
#Survival
Survival = tk.Label(self, text="Value of Survival Rates between 0-1")
Survival.pack()
survivala= tk.Label(self, text= 'Survival rates of Adults')
survivalaa = tk.Entry(self)
survivala.pack()
survivalaa.pack()
survival69= tk.Button(self, text="Enter", command = EnterSurvival)
survival69.pack()
survivaljj= tk.Label(self, text= 'Survival rates of Juvenile')
survivalj = tk.Entry(self)
survivaljj.pack()
survivalj.pack()
survival5 = tk.Button(self, text="Enter", command = EnterSurvival)
survival5.pack()
labelss= tk.Label(self, text= 'Survival rates of Seniles')
survivals = tk.Entry(self)
labelss.pack()
survivals.pack()
survival6 = tk.Button(self, text="Enter", command = EnterSurvival)
survival6.pack()
buttonS = tk.Button(self, text = "Birth Rates",
command=lambda: controller.show_frame("Birth"))
buttonS.pack()
class Birth(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Birth Rates", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
def EnterBirth(*args):
Birth1 = Birth2.get()
Birtha = tk.Label(self, text="Birth rates")
Birtha.pack()
Birth2 = tk.Entry(self)
Birth2.pack()
Birth3 = tk.Button(self, text="OK", command = EnterBirth)
Birth3.pack()
buttonB = tk.Button(self, text = "New Generatons",
command=lambda: controller.show_frame("NEW"))
buttonB.pack()
#Number of New Generations To Model
class NEW(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="New Generations", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
def EnterNew(*args):
print (New2.get())
news = New2.get()
New = tk.Label(self, text="Number of New Generatiions 5 - 25")
New.pack()
New2 = tk.Entry(self)
New2.pack()
New3 = tk.Button(self, text="OK", command = EnterNew)
New3.pack()
button = tk.Button(self, text="BACK To Home",
command=lambda: controller.show_frame("data"))
button.pack()
class data(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Data", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
no = tk.Button(self, text = "No",
command = lambda: controller.show_frame("Home"))
no.pack()
global Birth1
global s
global ss
global sss
global b1
global bj
global bs
global news
spja= b1 * s
spjb = bj * ss
spjs= bs * sss
st = spja + spjb + spjs
born = spja* rebirth
old = b1 + bj + bs
labelold = tk.Label(self, text = 'Orignal populaton'+str(old))
labelold.pack()
labelto = tk.Label(self, text='Adults that survived = '+str(spja)+ 'Juveniles = ' +str(spjb)+ 'Seniles = '+str(spjs)+ '/n Total= '+str(st))
labelto.pack()
Labelnew= tk.Label(self, text='New Juveniles = '+str(born))
Labelnew.pack()
# function for export data
class Quit(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Are you sure you want to quit?", font=TITLE_FONT)
label.pack(side="top", fill="x", pady=10)
yes = tk.Button(self, text="Yes", command = Exit)
yes.pack()
no = tk.Button(self, text = "No",
command = lambda: controller.show_frame("Home"))
no.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop(
</code></pre>
| <p>If you want to use global variables, you need to do this:</p>
<pre><code>var1 = <some value>
var2 = <some other value>
s1 = <yet another value here>
# then create your classes
class Whatever(tk.whatever_you_want):
def __init__(self, arg1, arg2, whatever_arg):
global var1 #whis tells the function to use the variable you defined already in the module scope
local_var_1 = var1 * 100 #
</code></pre>
<p>Of course, perhaps you don't know this already, global variables are usually considered bad to start with, but I don't think it matters much for you. It's going to matter when you modify and read the variables from waaay too many places to keep track of, but I'm not sure you're building that big of a script.</p>
|
PHP array_search not working (returns empty string) <p>I'm trying to check if a filename of an image contains "cover". Somehow this stopped working for me (Pretty sure it worked already). I copied the part of my function not working. </p>
<pre><code>$name=array("_IMG8555.jpg", "_IMG7769.jpg", "_IMG8458.jpg", "Cover.jpg", "_IMG7184.jpg");
$cov=array("Cover.png","Cover.jpg","Cover.jpeg", "cover.png","cover.jpg","cover.jpeg");
</code></pre>
<p>This does not work for me:</p>
<pre><code>print_r(array_search($cov, $name)); //Returns empty String
print_r($name[array_search($cov, $name)]); //Returns first element of the name Array
</code></pre>
<p>Also I added a test Strings to make sure this is not result the searched string is the same as the search value.</p>
<pre><code>print_r($name[3]===$cov[1]); //Returns true(1)
</code></pre>
<p>Can anyone help? Why does this simple script not work?</p>
<p>I also tried using <code>in_array()</code> but this is not working either.</p>
| <p>The array_search() function search an array for a value and returns the key</p>
<pre><code>array_search(key_value,array)
</code></pre>
<p>Loop your $cov array and get one key at a time and check with $name array</p>
<pre><code>foreach($cov as $i => $cov_s){
if(in_array($cov_s, $name)){
return $name[array_search($cov_s, $name)];
}
}
return $name[0];
</code></pre>
|
shopify I need to check if current page is a collection page and not a single product page <p>I am trying to check if my current page is a collection page not a single product page in some collection.</p>
<p>I mean for example if someone goes to collection page of shoes then I can check using collection.handle == 'Shoes' but if I select a product from that page then it will still give me true But I want my condition to be true on if it is collection page.
Thanks for your Help!</p>
| <p>Use this simple way with <a href="https://help.shopify.com/themes/liquid/objects/template" rel="nofollow"><code>template</code></a>: </p>
<pre><code>{% if template contains 'collection' %}
Do something
{% endif %}
</code></pre>
|
Can't launch service with net.tcp binding error 10049 <p>I have a problem with launching a WCF service using net.tcp endpoints. I'm getting an 10049 error.</p>
<p>My <code>app.config</code>:</p>
<pre><code><system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehaviour0"
name="Tinkl.Server.Services.Authentication.AuthenticationService">
<endpoint name="httpEndpoint"
address="reg"
binding="basicHttpBinding"
contract="Tinkl.Server.Services.Authentication.IRegistrationService" />
<endpoint name="httpEndpoint"
address="auth"
binding="basicHttpBinding"
contract="Tinkl.Server.Services.Authentication.IAuthorizationService" />
<!--
<endpoint name="tcpEndpoint"
address="net.tcp://78.26.210.203:50050/reg"
binding="netTcpBinding"
contract="Tinkl.Server.Services.Authentication.IRegistrationService" />
<endpoint name="tcpEndpoint"
address="net.tcp://78.26.210.203:50051/auth"
binding="netTcpBinding"
contract="Tinkl.Server.Services.Authentication.IAuthorizationService" />
-->
<endpoint name="mexEndpoint"
address="mex"
binding="mexHttpBinding" bindingConfiguration=""
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://78.26.210.203:50076/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour0">
<!--<serviceMetadata />-->
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</code></pre>
<p>There are 2 endpoints with <code>netTcpBinding</code> and 2 same exact with <code>basicHttpBinding</code>.</p>
<p>The problem appears when I'm trying to use <code>netTcpBinding</code> endpoints, I'm getting an error, but with <code>basicHttpBinding</code> it works fine...</p>
<p><a href="http://i.stack.imgur.com/W8X5O.png" rel="nofollow"><img src="http://i.stack.imgur.com/W8X5O.png" alt="enter image description here"></a></p>
<p>I'm hosting the WCF service in a console application.</p>
<p>Program code</p>
<pre><code>ServiceHost authenticationHost = new ServiceHost(typeof(AuthenticationService));
authenticationHost.Open();
Console.WriteLine("close <ENTER>\n");
Console.ReadLine();
authenticationHost.Close();
</code></pre>
<p>Maybe someone faced a similar problem?</p>
<p>If needed, I will give all the necessary additional information</p>
<p>Thank you in advance!</p>
| <p>Try to replace lines</p>
<pre><code>net.tcp://78.26.210.203:50050/reg
</code></pre>
<p>with </p>
<pre><code>net.tcp://localhost:50050/reg
</code></pre>
<p>And the same for <code>/auth</code> endpoint.</p>
|
Change table Information <p>I have three tables:</p>
<p>Table 1: (Consumer)</p>
<pre><code>UserName | FirstName | LastName
'Magika12' 'Ronald' 'Ludwig'
</code></pre>
<p>Table 2: (ConsumerLocation)</p>
<pre><code>UserName | LocationID
'Magika12' 13234
</code></pre>
<p>Table 3: (Location)</p>
<pre><code>LocationID | StreetNumber | StreetName | Suburb | City | Postalcode
13234 13 Baker Street Melton Brisbane 4242
</code></pre>
<p>And I would like to change the address of <code>Magika12</code> to this instead:</p>
<pre><code>"124 Braelands Crescent, Albion, Melbourne, 9999"
</code></pre>
<p>Whereby the new table would look like:</p>
<pre><code>LocationID | StreetNumber | StreetName | Suburb | City | Postal code
13234 124 Braelands Crescent Albion Melbourne 9999
</code></pre>
<p>I have tried something like this:</p>
<pre><code>UPDATE
L1
SET
L1.StreetNumber = 124,
L1.StreetName = 'Braelands Crescent',
L1.Suburb = 'Albion' ,
L1.City = 'Melbourne',
L1.Postalcode = 9999
FROM Location L1
INNER JOIN ConsumerLocation
WHERE ConsumerLocation.UserName = 'Magika'
</code></pre>
<p>I know this is not correct, But I am not sure how to connect all the tables together to update the address of <code>Magika12</code>. I have made <code>UserName</code> the primary key of <code>Consumer</code>, and the primary foreign key of <code>ConsumerLocation</code>. And <code>LocationId</code> the primary key of <code>Location</code> and the primary foreign key of <code>Consumer Location</code>. </p>
<p>Any help would be appreciated</p>
| <p>You missed condition of <code>join</code> statement. Should be like this:</p>
<pre><code>UPDATE
Location L1
INNER JOIN ConsumerLocation c on c.LocationID=L1.LocationID -- miseed on
SET
L1.StreetNumber = 124,
L1.StreetName = 'Braelands Crescent',
L1.Suburb = 'Albion' ,
L1.City = 'Melbourne',
L1.Postalcode = 9999
WHERE c.UserName = 'Magika'
</code></pre>
|
How modules know each other <p>I can plot data from a CSV file with the following code:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test0.csv',delimiter='; ', engine='python')
df.plot(x='Column1', y='Column3')
plt.show()
</code></pre>
<p>But I don't understand one thing. How <code>plt.show()</code> knows about <code>df</code>? I'll make more sense to me seeing, somewhere, an expression like:</p>
<pre><code>plt = something(df)
</code></pre>
<p>I have to mention I'm just learning Python.</p>
| <p>Matplotlib has two "interfaces": a <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html" rel="nofollow">Matlab-style interface</a> and an <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html" rel="nofollow">object-oriented interface</a>. </p>
<p>Plotting with the Matlab-style interface looks like this:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
</code></pre>
<p>The call to <code>plt.plot</code> implicitly creates a figure and an axes on which to draw.
The call to <code>plt.show</code> displays all figures.</p>
<p>Pandas is supporting the Matlab-style interface by implicitly creating a figure and axes for you when <code>df.plot(x='Column1', y='Column3')</code> is called.</p>
<p>Pandas can also use the more flexible object-oriented interface, in which case
your code would look like this:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test0.csv',delimiter='; ', engine='python')
fig, ax = plt.subplots()
df.plot(ax=ax, x='Column1', y='Column3')
plt.show()
</code></pre>
<p>Here the axes, <code>ax</code>, is explicitly created and passed to <code>df.plot</code>, which then
calls <code>ax.plot</code> under the hood.</p>
<p>One case where the object-oriented interface is useful is when you wish to use
<code>df.plot</code> more than once while still drawing on the same axes:</p>
<pre><code>fig, ax = plt.subplots()
df.plot(ax=ax, x='Column1', y='Column3')
df2.plot(ax=ax, x='Column2', y='Column4')
plt.show()
</code></pre>
|
How To Run a specific Application on Android Devices <p>I just want to learn how can i run my application on Android devices? <br>
I mean,it has to run automatically on startup and nothing will be allowed except the application.<br>
I just want to do something like this. (See the video) <a href="https://www.youtube.com/watch?v=09F3byGTdZs" rel="nofollow">https://www.youtube.com/watch?v=09F3byGTdZs</a>
<br>
Additional Explanation:<br>
I created an application.I want to run this on my tablet pc and everything else will be disabled except my application.When i start my tablet,my application will run directly and it's not allowed to go home screen,task manager or anything.Only my application will run on system.For example i got an application like instagram.I want to turn my android device to instagram device.I hope you understand.So sorry for bad english. </p>
| <p>Use this link for Kiosk Application
<a href="http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/" rel="nofollow">http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/</a></p>
|
solr 6.2.1 uniqueField not work <p>i install solr 6.2.1 and in schema define a uniqueField:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Solr managed schema - automatically generated - DO NOT EDIT -->
<schema name="ps_product" version="1.5">
<fieldType name="int" class="solr.TrieIntField" positionIncrementGap="0" precisionStep="0"/>
<fieldType name="long" class="solr.TrieLongField" positionIncrementGap="0" precisionStep="0"/>
<fieldType name="string" class="solr.TextField" omitNorms="true" sortMissingLast="true"/>
<fieldType name="uuid" class="solr.UUIDField" indexed="true"/>
<field name="_version_" type="long" multiValued="false" indexed="true" stored="true"/>
<field name="id_product" type="uuid" default="NEW" indexed="true" stored="true"/>
<uniqueKey>id_product</uniqueKey>
<field name="name" type="string" indexed="true" stored="true"/>
<field name="title" type="string" multiValued="false" indexed="true" required="true" stored="true"/>
</schema>
</code></pre>
<p>and my data-config like bellow:</p>
<pre><code><dataConfig>
<dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/pressdb-local" user="sa" password="" />
<document>
<entity name="item" query="select * from ps_product as p inner join ps_product_lang as pl on pl.id_product=p.id_product where pl.id_lang=2"
deltaQuery="select id from ps_product where date_upd > '${dataimporter.last_index_time}'">
<field name="name" column="name"/>
<field name="id_product" column="id_product"/>
<entity name="comment"
query="select title from ps_product_comment where id_product='${item.id_product}'"
deltaQuery="select id_product_comment from ps_product_comment where date_add > '${dataimporter.last_index_time}'"
parentDeltaQuery="select id_product from ps_product where id_product=${comment.id_product}">
<field name="title" column="title" />
</entity>
</entity>
</document>
</dataConfig>
</code></pre>
<p>but when i want to define a core in solr, give me error:</p>
<pre><code>Error CREATEing SolrCore 'product': Unable to create core [product] Caused by: QueryElevationComponent requires the schema to have a uniqueKeyField.
</code></pre>
<p>please help me to solve this problem.</p>
| <p>Since Solr 4 and to support SolrCloud the <a href="http://wiki.apache.org/solr/UniqueKey#UUID_techniques" rel="nofollow">uniqueKey</a> field can no longer be populated using <code>default=...</code> you should remove it from the feld definition in schema.xml :</p>
<p><code><field name="id_product" type="uuid" indexed="true" stored="true"/></code></p>
<p><strong>Update</strong>: As pointed out by MatsLindh, it seems you are using Solr in <a href="https://cwiki.apache.org/confluence/display/solr/Schemaless+Mode" rel="nofollow">schemaless mode</a>. Schema updates in this mode must be done via the <a href="https://cwiki.apache.org/confluence/display/solr/Schema+API" rel="nofollow">Schema API</a>, you should not edit the managed schema (<code><!-- Solr managed schema - automatically generated - DO NOT EDIT --></code>). To define <em>id_product</em> and <em>uniqueKey</em> field, use the API or <a href="http://stackoverflow.com/a/29822002/2529954">revert to the classic schema</a> mode.</p>
<p>To generate a uniqueKey to any document being added that does not already have a value in the specified field you can use UUIDUpdateProcessorFactory (cf. <a href="https://cwiki.apache.org/confluence/display/solr/Update+Request+Processors" rel="nofollow">Update Request Processor</a>). You will need to define an update processor chain in solrconfig.xml : </p>
<pre><code> <updateRequestProcessorChain name="uuid">
<processor class="solr.UUIDUpdateProcessorFactory">
<str name="fieldName">id_product</str>
</processor>
<processor class="solr.RunUpdateProcessorFactory" />
</updateRequestProcessorChain>
</code></pre>
<p>Then specify the use of the processor chain via the request param <code>update.chain</code> in your request handler definition.</p>
|
Workaround for Zoom in Graph overview? <p>I am currently working on a medium size graph in gephi (5k nodes, 25k edges);</p>
<p>Whenever I click on "Center on Graph" button, the Zoom slider stops working. If the file is saved in this situation, this error stays even after reopening Gephi. </p>
<p>Closing this graph file and opening other file makes the Zoom starting working again.</p>
<p>Is there a way to fix the Zoom slider? If not, any workaround to zoom in and out without the slider? (for instance, using the script console...)</p>
| <p>After doing some tests, I realized that an easy way to fix the problem is using the mouse wheel.</p>
<p>It changes the zoom level, and also fix the zoom slider.</p>
|
Websphere 8.5. won't start up after Java 7 SDK update <p>We have a Websphere 8.5 with Fix Pack 5 config, first we did use Java SDK 7.1.2.10. I removed this and installed Java SDK 7.1.3.40 but now I won't start the DMGR or nodes. I also doesn't start when I switch too Java SDK 6.</p>
<p>This is the error we get:</p>
<pre><code>JVMJ9VM134W The system fullcore option is set to FALSE, system dumps may be truncated.
Exception in thread "main" java/lang/NoClassDefFoundError: com.ibm.tenant.TenantGlobals
at java/lang/ClassLoader.initializeClassLoaders (ClassLoader.java:127)
at java/lang/Thread.initialize (Thread.java:370)
at java/lang/Thread.<init> (Thread.java:133)
JVMJ9VM015W Initialization error for library jclse7b_27(14): JVMJ9VM009E J9VMDllMain failed
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code></pre>
<p>Also I don't see anything wrong in the following:</p>
<pre><code>./managesdk.sh -listAvailable -verbose
CWSDK1003I: Available SDKs :
CWSDK1005I: SDK name: 1.6_64
- com.ibm.websphere.sdk.version.1.6_64=1.6
- com.ibm.websphere.sdk.bits.1.6_64=64
- com.ibm.websphere.sdk.location.1.6_64=${WAS_INSTALL_ROOT}/java
- com.ibm.websphere.sdk.platform.1.6_64=aix
- com.ibm.websphere.sdk.architecture.1.6_64=ppc_64
- com.ibm.websphere.sdk.nativeLibPath.1.6_64=${WAS_INSTALL_ROOT}/lib/native/aix/ppc_64/
CWSDK1005I: SDK name: 1.7.1_64
- com.ibm.websphere.sdk.version.1.7.1_64=1.7.1
- com.ibm.websphere.sdk.bits.1.7.1_64=64
- com.ibm.websphere.sdk.location.1.7.1_64=${WAS_INSTALL_ROOT}/java_1.7.1_64
- com.ibm.websphere.sdk.platform.1.7.1_64=aix
- com.ibm.websphere.sdk.architecture.1.7.1_64=ppc_64
- com.ibm.websphere.sdk.nativeLibPath.1.7.1_64=${WAS_INSTALL_ROOT}/lib/native/aix/ppc_64/
CWSDK1001I: Successfully performed the requested managesdk task.
</code></pre>
<p>After this I uninstalled Java SDK 7.1.3.40 and installed the previous version .7.1.2.10 again and now the DMGR and nodes start without a problem.</p>
| <p>Since there is no fixpack 5 for WebSphere Application Server traditional 8.5, I assume you're talking about 8.5.5 fixpack 5 or 8.5.5.5. According to <a href="http://www-01.ibm.com/support/docview.wss?uid=swg27005002" rel="nofollow">http://www-01.ibm.com/support/docview.wss?uid=swg27005002</a>, 8.5.5.5 is shipped with Java SDK 7.1.2.10, but you said you removed that and installed Java SDK 7.1.3.40. The only way you could safely do that would be to install a later fixpack but I don't see any 8.5.5 fixpack listed on the above page as shipping with SDK 7.1.3.40. This may explain why your server is broken and even installing Java 6 doesn't fix the issue. It is key to remember that you can not manually service the SDK level of WebSphere Application Server traditional, it can only be serviced by installing fixpacks. If you need a WebSphere Application Server where you can bring your own JDK, consider Liberty instead. </p>
|
How to pass/make an object/variable accessible inside a callback function which is called by a third party library? <p>How to make <code>globalObject</code> accessible by <code>callbackFunction</code>?</p>
<p>I am using a third party library <code>library.h</code> which has a method <code>libraryFunction</code>. The output of <code>libraryFunction</code> is a <code>libraryFunctionOutput</code> which is passed into the callback function <code>callbackFunction</code>.</p>
<p>How to pass another object (e.g. <code>globalObject</code>) for use inside the callback function <code>callbackFunction</code>?</p>
<p>Unfortunately the third party library is compiled so I cannot make any changes to it.</p>
<pre><code>#include <stdio.h>
#include "library.h"
int callbackFunction(int libraryFunctionOutput):
printf("%s, %d", libraryFunctionOutput, globalObject);
return 1;
int main(int argc, char* argv[])
{
int globalObject = 0;
libraryFunction(callbackFunction);
}
</code></pre>
<p>In the documentation, the function is shown as:</p>
<pre><code>int __stdcall libraryFunction(const char* filename,
unsigned int flags,
int userID,
MathrelCallback callbackFunction);
</code></pre>
<p>The <code>MathrelCallback</code> struct is defined as the following:</p>
<pre><code>struct MathrelCallback {MathrelHeader header;
MathrelInfo data;
unsigned int Type;
};
</code></pre>
| <p>If the library really takes a function pointer (not a generalized Callable like std::function) and does not offer the ability to pass a context or user pointer to your callback, you have to make your global object global (with all its drawbacks):</p>
<pre><code>#include <stdio.h>
#include "library.h"
static int globalObject = 0;
int callbackFunction(int libraryFunctionOutput)
{
printf("%s, %d", libraryFunctionOutput, globalObject);
return 1;
}
int main(int argc, char* argv[])
{
libraryFunction(callbackFunction);
}
</code></pre>
|
Collatz Structure Loop <p>I am trying to create a Collatz structure that asks the user how many times they would like to run it. Then it loops the code incrementing each time by 3 (n = n + 3). While the code partially works, it continues to repeat the previous process that is finished, e.g. with an input of 5 and running the process 3 times "Child 1 = 5, 16, 8, 4, 2, 1" and "Child 2 = 8,4,2,1" and "Child 3 = 11,34,17,52,26,13,etc."<br>
The issue is, it is looping too many times and running each Child multiple times. One time it is correct and the second time it runs it, it starts the sequence at "1."<br>
I am running this from a Linux Debian. To compile I use "gcc -o filename filename.c" and then to execute I use "./filename 5" where 5 is the number passed to "n" for the Collatz structure. Then it prompts how many times to run the loop.<br>
I understand I am probably way off, but I am completely lost and would greatly appreciate any assistance.</p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int n, j, x;
printf ("How many times would you like this to run?\n");
scanf ("%d",&j);
if (argc == 1) {
fprintf (stderr,"Usage: ./a.out <starting value>\n");
return -1;
}
printf("\nMain program's process ID: %d\n",getpid());
n = atoi(argv[1]);
for (x=1; x <= j; x++){
pid = fork();
if (pid < 0) {
fprintf(stderr, "Unable to fork child\n");
return -1;
}
else if (pid == 0) { /*child process */
printf("\nChild %d (ID: %d)\n",x,getpid());
printf("\nStart sequence at: %d\n",n);
while (n != 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
printf("\n(Child %d) %d ",x,n);
}
printf("\n\nAbout to end execution (I'm process %d) .\n",getpid());
}
else { /* parent process */
wait(NULL);
n = n + 3;
}
}
return 0;
}
</code></pre>
| <p>It looks to me like you aren't terminating the child process once it completes, you're just letting it continue the parent's main loop spawning more processes. Also, you were running a process and waiting for it which buys you nothing over letting your parent process just do the calculations -- instead spawn all the children and wait for them to finish, each in its own time. I've reworked your code to incorporate the above and some style tweaks:</p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
if (argc == 1) {
fprintf(stderr,"Usage: ./a.out <starting value>\n");
return EXIT_FAILURE;
}
int j;
printf ("How many times would you like this to run?\n");
scanf ("%d", &j);
(void) fpurge(stdin);
printf("\nMain program's process ID: %d\n", getpid());
int n = atoi(argv[1]);
for (int x = 1; x <= j; x++) {
pid_t pid = fork();
if (pid == -1) {
fprintf(stderr, "Unable to fork child\n");
return EXIT_FAILURE;
} else if (pid == 0) { /* child process */
pid_t child_pid = getpid();
printf("\nChild %d (ID: %d)\n", x, child_pid);
printf("\nStart sequence at: %d\n", n);
while (n != 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
printf("\n(Child %d) %d ", x, n);
}
printf("\n\nAbout to end execution (I'm process %d).\n", child_pid);
return EXIT_SUCCESS; /* child terminates */
}
else { /* parent process */
n = n + 3;
}
}
for (int x = 1; x <= j; x++) {
wait(NULL);
}
return EXIT_SUCCESS;
}
</code></pre>
<p><strong>SAMPLE RUN</strong></p>
<pre><code>> ./a.out 5
How many times would you like this to run?
4
Main program's process ID: 1164
Child 1 (ID: 1165)
Start sequence at: 5
(Child 1) 16
(Child 1) 8
(Child 1) 4
(Child 1) 2
(Child 1) 1
About to end execution (I'm process 1165).
Child 3 (ID: 1167)
Start sequence at: 11
(Child 3) 34
(Child 3) 17
(Child 3) 52
(Child 3) 26
(Child 3) 13
Child 2 (ID: 1166)
(Child 3) 40
(Child 3) 20
Start sequence at: 8
(Child 3) 10
(Child 3) 5
(Child 2) 4
(Child 3) 16
(Child 2) 2
(Child 3) 8
(Child 2) 1
(Child 3) 4
(Child 3) 2
About to end execution (I'm process 1166).
(Child 3) 1
About to end execution (I'm process 1167).
Child 4 (ID: 1168)
Start sequence at: 14
(Child 4) 7
(Child 4) 22
(Child 4) 11
(Child 4) 34
(Child 4) 17
(Child 4) 52
(Child 4) 26
(Child 4) 13
(Child 4) 40
(Child 4) 20
(Child 4) 10
(Child 4) 5
(Child 4) 16
(Child 4) 8
(Child 4) 4
(Child 4) 2
(Child 4) 1
About to end execution (I'm process 1168).
>
</code></pre>
<p>If the out of order results bother you, consider using threads and returning the results to be printed by the main thread or use some sort of locking to syncronize the output. Or have the children write the results to temporary files or pipes that the parent summarizes at the end.</p>
<p>One final style note, don't return -1 from <code>main()</code>, nor do <code>exit(-1)</code> -- although returning -1 indicates an error for system subroutines, the value returned by <code>main()</code> to the operating system should be in the range 0 (success) to 255 with 1 (failure) being a generic error indicator.</p>
|
Device build fails after upgrading to Xcode 8 <p>Since upgrading to Xcode 8 I cannot run any app on my iPhone. The build fails with error:</p>
<blockquote>
<p>error: Task failed with exit 0 signal 11</p>
</blockquote>
<p>I can run the apps on the simulators, just not on a device.
The full error message:</p>
<blockquote>
<p>error: Task failed with exit 0 signal 11 { /usr/bin/codesign
'--force' '--sign' '7F49C2A625C8976762BDEA351F8DA88E4F6FED22'
'--verbose'
'/Users/reshef/Library/Developer/Xcode/DerivedData/testXcode-eltpwhxdshmmlygolxcnsroevmoo/Build/Products/Debug-iphoneos/testXcode.app/Frameworks/libswiftCore.dylib'
}</p>
</blockquote>
| <p>Use automatically manage signing:</p>
<p>Go to Target --> General --> Signing, check the Automatically manage siging.</p>
|
get the data associate with cell in Selected event <p>I am doing a form generator app to be developed in jquery/javascript.
I am using a html table an in order the cell to be selectable I am using jquery 'selectable' api. I have attached some metadata to the cells while initializing the cells and now I want to access that in 'selected' event. But some how it is not accessible. </p>
<pre><code>$("#form_table").selectable({
filter: "td",
selected: function (event, ui) {
populatepropgrid(ui.data("element"));
}
});
</code></pre>
<p>ui.data is always undefined in above code. I am new to jquery so sorry for such a easy question.</p>
| <p>You can get the <code>data-element</code> attribute of the selected cell with:</p>
<pre><code>$(ui.selected).data("element")
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#form_table").selectable({
filter: "td",
selected: function (event, ui) {
console.log("Selected: " + $(ui.selected).data("element"));
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code> td.ui-selecting { background: #FECA40; }
td.ui-selected { background: #F39814; color: white; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<table id="form_table">
<tr>
<td class="ui-widget-content" data-element="elem1">Element 1</td>
<td class="ui-widget-content" data-element="elem2">Element 2</td>
<td class="ui-widget-content" data-element="elem3">Element 3</td>
</tr>
<tr>
<td class="ui-widget-content" data-element="elem4">Element 4</td>
<td class="ui-widget-content" data-element="elem5">Element 5</td>
<td class="ui-widget-content" data-element="elem6">Element 6</td>
</tr>
</table></code></pre>
</div>
</div>
</p>
|
How to sum all elements in a tuple <p>In Swift, i.e. a tuple <code>let tp = (2,5,8)</code>.</p>
<p>What's the simplest and smartest way to sum it up, other than traditionaly as below?</p>
<p><code>let sum = tp.0 + tp.1 + tp.2</code></p>
| <p>Your approach is the most straightforward. An alternative is harder to read, but it works, too:</p>
<pre><code>let s = Mirror(reflecting: x).children.map {$1 as! Int}.reduce(0,+)
</code></pre>
<p><code>Mirror(reflecting: x).children</code> obtains a sequence of name-value pairs representing the original tuple. Each element of the sequence is a <code>(String,Any)</code> tuple. <code>map {$1 as! Int}</code> converts this sequence to a sequence of <code>Int</code>s representing tuple element values; <code>reduce(0,+)</code> produces the sum of these values.</p>
<p>You can combine <code>map</code> and <code>reduce</code> in a single expression for something even less readable:</p>
<pre><code>let s = Mirror(reflecting: x).children.reduce(0,{$0.1.value as! Int + $0.0})
</code></pre>
<p><strong>Note:</strong> It goes without saying that this crashes at runtime for tuples containing values of type other than <code>Int</code>.</p>
|
ReactiveCocoa, Module compiled with Swift 2.3 cannot be imported in Swift 3.0 issue. How to fix? <p>I have 2 Xcodes in my Mac(7.3.1 & 8.1). I want to work with ReactiveCocoa so I installed it via Cocoapods and later with Carthage. And when I import later in my ViewController <code>import ReactiveCocoa</code> I get the next error:</p>
<pre><code>Module compiled with Swift 2.3 cannot be imported in Swift 3.0: /Users/myUser/Library/Developer/Xcode/DerivedData/RAC-grddczfrbaumbtglfcuzhxyzoodk/Build/Products/Debug-iphonesimulator/ReactiveCocoa.framework/Modules/ReactiveCocoa.swiftmodule/x86_64.swiftmodule
</code></pre>
<p>How can I fix that? I'm already working over it over 3-4 hours and nothing</p>
| <p>Referring to the latest <a href="https://github.com/ReactiveCocoa/ReactiveCocoa" rel="nofollow">documentation</a> (github):</p>
<blockquote>
<p>"This documents the RAC 5 which targets Swift 3.0.x ..."</p>
</blockquote>
<p>I assume that should not install 4.x version. try to "pod 'ReactiveCocoa'" -for installing the latest version-, version 5 for targeting Swift 3.</p>
<p>Also, check the section "<a href="https://github.com/ReactiveCocoa/ReactiveCocoa#objective-c-and-swift" rel="nofollow">Objective-C and Swift</a>".</p>
<p>Hope that helped.</p>
|
Return count of records in SQL <p>I have one table like
â</p>
<pre><code>âSQL> select * from CRICKET_DETAILS;
TEAM1 TEAM2 WINNER
-------------------- -------------------- --------------------
INDIA PAKISTAN INDIA
INDIA SRILANKA INDIA
SRILANKA INDIA INDIA
PAKISTAN SRILANKA SRILANKA
PAKISTAN ENGLAND PAKISTAN
SRILANKA ENGLAND SRILANKA
6 rows selected.
â
</code></pre>
<p>I want output like this:</p>
<pre><code>TEAM PLAYED WON LOST
ENGLAND 2 0 2
INDIA 3 3 0
PAKISTAN 3 1 2
âSRILANKA 4 2 2
</code></pre>
| <p>I would go with <code>group by</code> and <code>union all</code>:</p>
<pre><code>select team, count(*), sum(won), sum(lost)
from ((select team1 as team,
(case when winner = team1 then 1 else 0 end) as won,
(case when winner = team1 then 0 else 1 end) as lost
from cricket_details cd
) union all
(select team2,
(case when winner = team2 then 1 else 0 end) as won,
(case when winner = team2 then 0 else 1 end) as lost
from cricket_details cd
)
) tt
group by team;
</code></pre>
|
How to read 2 different dataframes from single CSV file in R? <p>Suppose we have 2 dataframes like this in single CSV file as:</p>
<pre><code>Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 2 6
#
Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 3 6
</code></pre>
<p>My actual requirement is to read these 2 dataframes in 2 different dataframe variables, I want to analyze these 2 dataframes and plot accordingly, please help me in this regard.</p>
| <p>Here's an example</p>
<pre><code>writeLines(
con = tf <- tempfile(fileext = ".csv"),
text = "Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 2 6
#
Name C1 C2 C3 C4
aa 1 2 3 4
bb 3 4 6 5
cc 10 2 5 6
TT 44 2 3 6")
txt <- readLines(tf)
sep <- grep("^#", txt)[1]
df1 <- read.table(text = txt[1:(sep-1)], header = TRUE)
df1$part <- "1"
df2 <- read.table(text = txt[(sep+1):length(txt)], header = TRUE)
df2$part <- "2"
library(tidyr)
library(dplyr)
library(ggplot2)
bind_rows(df1, df2) %>%
gather(var, val, -part, -Name) %>%
ggplot(aes(x = Name, y = val, fill = var)) +
geom_col() +
facet_wrap(~part)
</code></pre>
<p><a href="http://i.stack.imgur.com/tnZo7.gif" rel="nofollow"><img src="http://i.stack.imgur.com/tnZo7.gif" alt="enter image description here"></a></p>
|
Dagger 2 : error while getting a multiple instances of same object with @Named <p>How can i get multiple instances of same return type like cursor </p>
<p>for example :-</p>
<pre><code>Module
@CursorScope
public class CursorModule {
@Provides
Cursor provideSongCursor(
@Named("Song") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID,
MediaStore.Audio.AudioColumns.TITLE,
MediaStore.Audio.AudioColumns.ARTIST,
MediaStore.Audio.AudioColumns.ALBUM,
MediaStore.Audio.AudioColumns.DURATION
}, MediaStore.Audio.AudioColumns.IS_MUSIC + "=1", null, null);
}
@Provides
Cursor provideAlbumCursor(
@Named("Album") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID,
MediaStore.Audio.AlbumColumns.ALBUM,
MediaStore.Audio.AlbumColumns.ARTIST,
MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,
MediaStore.Audio.AlbumColumns.FIRST_YEAR
}, null, null, null);
}
@Provides
Cursor provideArtistCursor(@Named("Artist") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
new String[] {
BaseColumns._ID,
MediaStore.Audio.ArtistColumns.ARTIST,
MediaStore.Audio.ArtistColumns.NUMBER_OF_ALBUMS,
MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS
}, null, null,null);
}
@Provides
Cursor provideGenreCursor(
@Named("Genres") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
new String[] {
BaseColumns._ID,
MediaStore.Audio.GenresColumns.NAME
}, null, null, null);
}
@Provides
Cursor providePlaylistCursor(@Named("Playlist") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] {
BaseColumns._ID,
MediaStore.Audio.PlaylistsColumns.NAME
}, null, null, null);
}
}
</code></pre>
<p>which is provided in</p>
<pre><code>@CursorScope
@Subcomponent(modules = CursorModule.class)
public interface CursorComponent {
Cursor cursor();
}
</code></pre>
<p>I get this error </p>
<pre><code>Error:(17, 11) Gradle: error: android.database.Cursor is bound multiple times:
@Provides android.database.Cursor com.merkmod.musician.dependency.CursorModule.provideSongCursor(@Named("Song") com.merkmod.musician.application.Musician)
@Provides android.database.Cursor com.merkmod.musician.dependency.CursorModule.provideAlbumCursor(@Named("Album") com.merkmod.musician.application.Musician)
@Provides android.database.Cursor com.merkmod.musician.dependency.CursorModule.provideArtistCursor(@Named("Artist") com.merkmod.musician.application.Musician)
@Provides android.database.Cursor com.merkmod.musician.dependency.CursorModule.provideGenreCursor(@Named("Genres") com.merkmod.musician.application.Musician)
@Provides android.database.Cursor com.merkmod.musician.dependency.CursorModule.providePlaylistCursor(@Named("Playlist") com.merkmod.musician.application.Musician)
</code></pre>
<p>I made multiple instances of Cursor and annotated with @Named at provider level first then it started giving me error with cannot be provided with @Provides annotation so i shifted to using it inside the constructor</p>
<p>like in the code above . The problem is running a cycle again and again and i am like stuck in getting the cursor stuff done , any help will be appreaciated.</p>
| <p>when you want to provide multiple variable of one type you must use <code>@Named</code> annotation like below:</p>
<pre><code>Module
@CursorScope
public class CursorModule {
@Provides
@Named("songCursor")
Cursor provideSongCursor(
@Named("Song") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID,
MediaStore.Audio.AudioColumns.TITLE,
MediaStore.Audio.AudioColumns.ARTIST,
MediaStore.Audio.AudioColumns.ALBUM,
MediaStore.Audio.AudioColumns.DURATION
}, MediaStore.Audio.AudioColumns.IS_MUSIC + "=1", null, null);
}
@Provides
@Named("albumCursor")
Cursor provideAlbumCursor(
@Named("Album") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{
BaseColumns._ID,
MediaStore.Audio.AlbumColumns.ALBUM,
MediaStore.Audio.AlbumColumns.ARTIST,
MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS,
MediaStore.Audio.AlbumColumns.FIRST_YEAR
}, null, null, null);
}
@Provides
@Named("artistCursor")
Cursor provideArtistCursor(@Named("Artist") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
new String[] {
BaseColumns._ID,
MediaStore.Audio.ArtistColumns.ARTIST,
MediaStore.Audio.ArtistColumns.NUMBER_OF_ALBUMS,
MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS
}, null, null,null);
}
@Provides
@Named("genreCursor")
Cursor provideGenreCursor(
@Named("Genres") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI,
new String[] {
BaseColumns._ID,
MediaStore.Audio.GenresColumns.NAME
}, null, null, null);
}
@Provides
@Named("playListCursor")
Cursor providePlaylistCursor(@Named("Playlist") Musician musician) {
return musician.getApplicationContext().getContentResolver().query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] {
BaseColumns._ID,
MediaStore.Audio.PlaylistsColumns.NAME
}, null, null, null);
}
}
</code></pre>
<p>then when you want to inject write like below:</p>
<pre><code>@Inject
@Named("soundCursor")
Cursor soundCursor;
@Inject
@Named("albumCursor")
Cursor albumCursor;
@Inject
@Named("artistCursor")
Cursor artistCursor;
@Inject
@Named("genreCursor")
Cursor genreCursor;
@Inject
@Named("playListCursor")
Cursor playListCursor;
</code></pre>
<p>if you wan to inject them in constructor injections do like below:</p>
<pre><code>@Inject
public SomeClassConstructor(@Named("album") Cursor cursur)
</code></pre>
<p>and what you have written in your subcomponent interface I cant get it what it is, it must be like:</p>
<pre><code>@CursorScope
@Subcomponent(modules = CursorModule.class)
public interface CursorComponent {
void inject(TheClassThatWantsToUseInject1 obj);
void inject(TheClassThatWantsToUseInject2 obj);
}
</code></pre>
<p>and in your application component:</p>
<pre><code> YourSubComponentInterface plus(CursorModule module);
</code></pre>
|
C++ output string without '\n' or endl will output '#' in the end of string <p>On ubuntu16.04, I use g++ to compile such code:</p>
<pre><code>#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}
</code></pre>
<p>if the string does not end with '\n' or use 'std::endl' at the last, the output will be<code>Hello World!#</code> I don't know why it ends with '#'</p>
| <p>It doesn't, it's your bash prompt.</p>
<p>You can reproduce your problem with <code>echo</code>:</p>
<pre class="lang-bash prettyprint-override"><code># echo "Hello, World!"
Hello, World!
# echo -n "Hello, World!"
Hello, World!#
</code></pre>
|
Exception handling in code layers in java <p>I have two layers in my project say A & B. Layer A functions throw set of exceptions Ae1, Ae2, Ae3. Layer B functions throw exceptions Be1, Be2,Be3, Be4. Layer B functions are called from different functions in Layer A. </p>
<p>A function in layer A can throws more than one exception. Similarly in layer B. </p>
<p>Also, I have a mapping like whenever I get exceptions Be1 and Be2 from Layer B functions, I <strong>catch</strong> those exceptions inside layer A function definition using try catch and throw it as Ae3. Similarly, exceptions Be3 is thrown as Ae2, and Be4 is thrown as Ae1. </p>
<pre><code>public void function1InLayerB throws Be1, Be2, Be4{
......
}
</code></pre>
<p>Now what I am doing is :</p>
<pre><code>public void function1InLayerA throws Ae3, Ae1{
try{
function1InLayerB();
} catch(Be1){
throw new Ae3;
} catch(Be2){
throw new Ae3;
} catch(Be4){
throw new Ae1;
}
}
</code></pre>
<p>So, I want to <strong>avoid such a lot of try catch blocks</strong>, by using a function or any other different approach and have function in layer A simple as </p>
<pre><code>public void fnuction1InLayerA throws Ae1, A2{
....
new_function(function1InLayerB());
}
</code></pre>
<p>Is it possible to write a common function like this ? </p>
<p>Note : Java version 6.</p>
| <p>Since Java 7 you can do this:</p>
<pre><code> try{
function1InLayerB();
} catch(Be1 | Be2){
throw new Ae3;
} catch(Be4){
throw new Ae1;
}
</code></pre>
<p>Thus you avoid repetition when the common exception happens in catch blocks.</p>
<p>For Java 6 and less:</p>
<pre><code>try{
function1InLayerB();
}catch(Exception ex){
manageExceptions(ex);
}
</code></pre>
<p>And create a method that checks the instance of the exception to manage it and throw the desired exception.</p>
<pre><code>private void manageExceptions(Exception ex){
if(ex instanceOf Be1 || ex instanceOf Be2){
throw new Ae3;
}else if(ex instance of Be4){
throw new Ae1;
}...
else
throw new Exception(ex);
}
</code></pre>
|
Energy drink scrape in python <p>I want to scrape the energy drink in india by ml</p>
| <p>If you have the IMDB id's use the MovieMeter API vs scraping:</p>
<pre><code>library(moviemeter) # devtools::install_github("hrbrmstr/moviemeter")
library(purrr)
imdb_ids <- c("tt1107846", "tt0282552", "tt0048199")
map_df(imdb_ids, function(x) {
mm <- mm_get_movie_info(x)
mm <- map(mm, ~. %||% NA) # the javascript has nulls, so get rid of them
mm[c(1:11)] # remove posters, countries, genres, actors and directors
}) -> df
dplyr::glimpse(df)
## Observations: 3
## Variables: 11
## $ id <int> 57161, 6465, 33351
## $ url <chr> "https://www.moviemeter.nl/film/57161", "https://www.moviemeter.nl/film/6465", "https://www.moviemeter.nl/film/33351"
## $ year <int> 2007, 2002, 1955
## $ imdb <chr> "tt1107846", "tt0282552", "tt0048199"
## $ title <chr> "Theft", "Riders", "Illegal"
## $ display_title <chr> "Theft", "Riders", "Illegal"
## $ alternative_title <chr> NA, "Steal", NA
## $ plot <chr> "Een naïeve dorpsjongen wordt verliefd op een crimineel. Guy was altijd een nette beschaafde jongen, wie had er ooi...
## $ duration <int> 90, 83, 88
## $ votes_count <int> 1, 293, 20
## $ average <dbl> 2.00, 2.55, 3.42
</code></pre>
<p>If you are trying to compare IMDB top 250 with MovieMeter top 250 then you have to scrape since their API is pretty limited. </p>
<p>Remember to cite them in anything you make from this work and be wary of scraping IMDB. LinkedIn sued a bunch of scrapers in 2016 and folks are going to be taking intellectual property even more seriously in the coming months/years.</p>
|
How to add < in TextInput. To show message like < Back <p>how can i insert < in TextInput. I want to show message like < Back.</p>
<p>I tried entering the < directly but it gives compile time error.</p>
<p>thanks in advance.</p>
| <p>You can wrap the text with brackets like that:</p>
<pre><code><Text>{'< Back'}</Text>
</code></pre>
|
Two Words in one String with space <p>I am trying to read inputs from file. I have line like this:
"Peter Brown Ashley Granger". There are two empty strings, name1 and name2. I want to get Peter Brown as name1 and Ashley Granger as name2. How can i do that ? </p>
| <p>Read the two parts, then put them together.</p>
<p>Something along these lines:</p>
<pre><code>std::string full_name;
std::string part1;
std::string part2;
if (stream >> part1 >> part2)
{
full_name = part1 + " " + part2;
}
</code></pre>
|
(Android + Firebase) Automatically sending push notifications on child added <p>So I'm trying to make a group chat for an Android app using Firebase. What I want to do is send automatic notifications to users whenever a child is added to the realtime database (i.e when someone else sends a message to the group chat I want the other users to get a notification, regardless of if the app is in the forground or not).</p>
<p>Does anyone have any experience doing this? I have been looking around and I haven't found any good answers. Not even sure it can be done using firebase.</p>
| <p>I believe this is not yet implemented on Firebase. I think you can ask them directly <a href="https://firebase.google.com/support/contact/bugs-features/" rel="nofollow">here</a>. </p>
|
Laravel CsrfToken expires on refresh after switching servers <p>I know my issue is not because of Laravel but most likely the php configuration (sessions), but I am not sure what to check. I was running this particular project on a <code>homestead</code> and it was fine. Now after I submit a form (it's a steps controller, <code>post</code> form -> go to step 2 etc.) and refresh the page my csrf token is invalid.</p>
<p>I thought it was because of session lifetime and such or generation of new token, but no .. the token is the same, but I still get <code>TokenMismatchException</code> after I refresh the page.</p>
<p>The environment is pretty much the same as the homestead (nginx (latest), php(5.6, I don't know what homestead had) ). The logins work fine, I stay logged in while browsing, but when I go through the steps this happens ..</p>
<p><strong>Problem & Solution:</strong></p>
<p>As per comments bellow where I forgot to update, I found out the problem was actually the fact, that the dev server was forced through cloudflare, but the base url in Laravel was left at <code>http://...</code> - I just added to <code>AppServiceProvider</code> </p>
<pre><code>$this->app['request']->server->set('HTTPS', true);
</code></pre>
<p>and it wasn't doing the verification error.</p>
| <p>Do you send a csrf token with the form you submit? If not: how did you build up your form, with FormBuilder or Html?</p>
<p><strong>FormBuilder</strong></p>
<p>In the formbuilder the CSRF token is already posted so it's not needed to send it.</p>
<p><strong>Html</strong></p>
<pre><code><form method="POST" action="/profile">
{{ csrf_field() }} //This is what you need!
...
</form>
</code></pre>
<p>You did not provide an error log, check in your laravel project for storage/logs and then provide us the error so we can help you.</p>
|
Spark container failed. Shall I trust the results I got? <p>I have a quite long Spark job only consisting of a map operation.
I tried to launch it several times with different number of partitions, executors, and the maximum amount of memory I could give (16G + 2G of overhead).
During my last attempt few executors were killed because of memory overheads, however, the output was produced and it seems ok (obviously, I couldn't check all the rows of my dataframe, though).
Moreover, I found a _SUCCESS file in the output directory.</p>
<p>Shall I trust the output I got?</p>
| <p>I think output will be correct because you have _SUCCESS file and also if some of you executor dies because of out of memory spark is fault tolerant so the work load will be transfer to the other executor.</p>
|
Typescript debug with line number <p>Opening up the console in a browser shows the javascript line number of a function call or error message.</p>
<p>But I am using TypeScript which is being compiled to Javascript.</p>
<p>Is there a way I can get the line numbers for TypeScript?</p>
<p>I am using VSCode as my editor</p>
| <p>There are source maps, but the simple thing to do is to navigate to the source, provided that for development it's not being uglified and rollified and minified, in that case you need source maps. </p>
<p>Otherwise simply using the generated JavaScript file usually points to what the issue might be in the source code. If this sounds cumbersome you can always open a side by side view of source and the built JS.</p>
|
Mac beeps when I type end parantheses in commented block of Python <p>Why, when I type an end parantheses in a commented out area in IDLE, does mac sound the error beep, and how can I stop it?</p>
| <p>Various programs, including IDLE, sometimes ask the computer to 'beep' when the user does something that the program considers an error. In general, to not hear a beep, you can 1) stop doing whatever provokes the beep, 2) turn your speaker down or off, or 3) plug in earphones and not wear them while editing.</p>
|
Unable to pass values to controller from jquery function <p>My Codeigniter view needs to pass <code>textbox</code> values to another function in the calling <code>controller</code> as follows. But when i click the mouse unable to pass values to controller from jquery function. Nothing happen in click event.</p>
<p><strong>Controller</strong></p>
<pre><code>class Main extends CI_Controller {
public function index() {
}
public function abc(){
$this->load->view('main_view');
$name = $_POST["name"];
}
public function display(){
$this->load->view('display_view');
//want to display name here
}
</code></pre>
<p><strong>main_view</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>< script type = "text/javascript" >
$(document).ready(function() {
var postUrl = '<?php echo base_url(); ?>' + 'main/display';
$("#send").click(function() {
$.post(postUrl, {name :name },function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
}); < /script></code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post">
<input id="textbox" type="text" name="textbox">
<input id="send" type="submit" name="send" value="Send">
</form></code></pre>
</div>
</div>
</p>
| <p>You are using ajax so first disable default form submission</p>
<pre><code>$("#send").click(function(e) {
e.prevenntDefault(); //default form submit
e.stopPropagation();
var postUrl = '<?php echo base_url(); ?>' + 'main/display';
name = $("#textbox").val();
$.post(postUrl, {name :name },function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
</code></pre>
<p>Now in <code>display()</code> get value and assign to view</p>
<pre><code>$name = $_POST["name"];
$data = array(
'name' => $name
);
$this->load->view('results_view', $data);
</code></pre>
<p>Now in view display that $name</p>
<pre><code>if(isset($name) && $name!='')
echo $name;
</code></pre>
<p>EDIT:</p>
<p>If don't want ajax use simple form submission fie form an <code>action</code></p>
<pre><code> <form method="post" action="your url for action" id="myForm">
</code></pre>
<p>then you can submit either by clicking submit or by jquery using <code>$("#myForm").submit();</code></p>
<p>Also check if you passing action urls for form action</p>
|
@Input with promise Angular2 <p>I have the parent component like this:</p>
<pre><code>import { Component } from '@angular/core';
import { UrlService } from '../../services/url.service';
@Component({
selector: 'wrapPost',
templateUrl: './app/html/wrapPost.component.html',
})
export class WrapPost {
dataPost: any;
url: string;
constructor(private urlService: UrlService) {}
ngOnInit(){
let url = window.location.pathname;
this.urlService.getData(url)
.then(res => this.dataPost = res);
}
}
</code></pre>
<p>there is get a dates from server and return <strong>this.dataPost</strong>.
That's well working.</p>
<p>This html of parent <code>templateUrl: './app/html/wrapPost.component.html'</code></p>
<pre><code><div class="noteCommonAlign">
<navigation></navigation>
<posts [dataPost]="dataPost"></posts>
<loading class="noteCommonAlign"></loading>
<pagination [dataPost]="dataPost"></pagination>
</div>
</code></pre>
<p>Further the component <strong>pagination</strong> (the child)</p>
<pre><code>import { Component, Input, SimpleChanges } from '@angular/core';
@Component({
selector: 'pagination',
templateUrl: './app/html/pagination.component.html',
styleUrls: ['app/css/pagination.component.css']
})
export class Pagination {
pagCurrent: number;
@Input() dataPost: any;
constructor(){
}
ngOnChanges(changes: SimpleChanges){
try{
console.log(this.dataPost);
} catch(err) {
console.log(err);
}
}
}
</code></pre>
<p>I can't get <strong>this.dataPost</strong> async. When i called without <em>ngOnChanges</em> console.log(this.dataPost) then happen a mistake. I resolved this problem a little. I Used <strong>ngOnChanges</strong> but in console showed 2 messages. One message with a mistake other with a great result.</p>
<p>How i understand it has happen because <strong>ngOnChanges</strong> is Lifecycle and called before ngOnInit and whenever one or more data-bound input properties change.
I wouldn't like that it's called twice.</p>
<p>How to get a dates from server in a child component has @Input? </p>
<p>I'm sorry for the grammar. I will be glad any solves. </p>
| <p>What about </p>
<pre><code><navigation></navigation>
<posts [dataPost]="dataPost | async"></posts>
<loading class="noteCommonAlign"></loading>
<pagination [dataPost]="dataPost | async"></pagination>
</code></pre>
|
C: main() returning an array always equals to 56 <p>I wonder what happens when I play with the return value of the <code>main</code> function.</p>
<p>I found that if I return an array variable from <code>main</code> (which is supposed to be the exit status) and print the exit status in shell, the output is always 56. I wonder why?</p>
<p>The C program:</p>
<pre><code>int* main(void) {
static int x[3];
x[0]=89;
x[1]=15;
x[2]=10;
return x;
}
</code></pre>
<p>I test it as follows:</p>
<pre><code>gcc array_return.c -o array_return
./array_return
echo $?
</code></pre>
<p>The output is always <code>56</code> even if I change the size of the array, or change the numbers in it. What does the number <code>56</code> mean?</p>
| <p>Your program returns a pointer. It's not an "array" as you put it in the question. Because the name of an array evaluates to the address of its first item (which is the same as address of the array itself).</p>
<p>In C, the value returned from the <code>main</code> function is interpreted as the <a href="https://en.wikipedia.org/wiki/Exit_status#C_language" rel="nofollow">exit status</a>, i.e. the <code>$?</code> variable used in your example.</p>
<p>I guess, you're running Bash shell, since in Bash the exit status is stored in the <code>$?</code> variable. A pointer is usually a big number, at least bigger than <strong>255</strong>, which is a maximum <a href="http://tldp.org/LDP/abs/html/exitcodes.html#AEN23629" rel="nofollow">exit code in Bash</a>:</p>
<blockquote>
<p>Out of range exit values can result in unexpected exit codes. An exit
value greater than 255 returns an exit code modulo 256. For example,
exit 3809 gives an exit code of 225 (3809 % 256 = 225).</p>
</blockquote>
<p>Now let's modify your program by printing the address of the variable, and the address <a href="https://en.wikipedia.org/wiki/Modulo" rel="nofollow">modulo</a> <strong>256</strong>:</p>
<pre><code>#include <stdio.h>
int main(void) {
static int x[3];
printf("%ld ==> %d\n", (size_t)x, (size_t)x % 256);
return (int)x;
}
</code></pre>
<p>Let's compile it and test if I'm right:</p>
<pre><code>$ gcc -Wall -g test.c -o test && ./test; echo $?
test.c: In function âmainâ:
test.c:6:12: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
return (int)x;
^
6295620 ==> 68
68
</code></pre>
<p>As we can see, the return status is equal to <code>6295620 % 256</code>, as it is documented in the <a href="http://tldp.org/LDP/abs/html/exitcodes.html" rel="nofollow">official documentation</a>.</p>
|
Convert phpMyAdmin exported database to older version. utf8mb4 issues <p>I want to move my MySQL database to an older version server (5.7 to 5.1).<br>
I get errors because it is created using <code>utf8mb4</code> .<br>
If i manually change <code>utf8mb4</code> to <code>utf8</code> the data become unreadable because of multilinguality.<br>
I have access only to phpMyAdmin in both servers so I can't use <code>mysqldump</code>.<br>
Any ideas?</p>
| <p>It seems I've figured out a solution.<br>
Use at export <code>mysql40</code> compatibility mode, replace <code>utf8mb4</code> with <code>utf8</code> and change the character set of tables from phpmyadmin to <code>utf8_unicode_ci</code>.<br>
Hope this will save some time from a fellow in future.</p>
|
How to select data from db using angular variable in php <p>I want to write select query in php to get data from database using variable from front-end. In other words I need to do something like this:
SELECT email FROM users WHERE token = '$token'
What I currently have, I have code which posts my variables to back end:</p>
<pre><code>app.controller('customersCtrl', function($scope, $http,$templateCache) {
$scope.subscribe = function (gameId){
$scope.codeStatus = "";
$http({
url: "php/test.php",
method: "POST",
data: {
userId: JSON.parse(localStorage.getItem('loggedUserInfo')),
gameId: gameId,
token:JSON.parse(localStorage.getItem('token'))
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).success(function(response) {
$scope.codeStatus = response.data;
console.log(response);
});
};
});
</code></pre>
<p>And here is my php code:</p>
<pre><code><?php
$lnk = mysql_connect('localhost', 'root', '')
or die ('Not connected : ' . mysql_error());
mysql_select_db('pitch', $lnk) or die ('Can\'t use db : ' . mysql_error());
$data = json_decode(file_get_contents("php://input"));
$token=$data->token;
$dump1 = mysql_query("SELECT email FROM users where token = '$token' ");
if(!$dump1) exit("Error - ".mysql_error());
$getList = array();
$outp = "";
while ($row = mysql_fetch_assoc($dump1)) {
$relations = array();
$getList[] = $row;
}
$output = json_encode(array('users' => $getList));
echo $output;
?>
</code></pre>
<p>The weirdest thing for me is that when I try to go to url localhost/php/test.php I get an Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/test.php on line 8, which means I guess that $token is empty, but when I console.log(response) in angular it shows me my token in console which I think means that data from front-end was passed to back-end. Or my understanding is wrong?</p>
<p>Will be really thankful for help!</p>
| <p>first thing is try to var_dump($_POST), or try to var_dump($data) on your test.php</p>
|
How to construct array of objects inside $.each(? <p>I have little experience with array of objects so please bare with me.
My current code pushes the key into normal array but i want to push both key and value in to array of object. I appreciate if an expert show me how this can be done.Thanks</p>
<p>Javascript to create the object array:</p>
<pre><code>var xml ='<?xml version="1.0" encoding="UTF-8"?> <dict><key>ItemLists</key> <array><dict><key>id</key> <string>1</string> <key>name</key> <string>fruits</string> <key>category</key> <string>US Fruits</string> <key>categoryIcon</key> <string>http://www.somsite.com/categories/1.jpg</string> <key>country</key> <string>US</string> </dict> <dict><key>id</key> <string>2</string> <key>name</key> <string>Vegetable</string> <key>category</key> <string>Eu Vegetable</string> <key>categoryIcon</key> <string>http://www.somsite.com/categories/2.jpg</string> <key>country</key> <string>EU</string> </dict> </array> </dict>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
var MyArray=[];
$(xml).find("array key").each(function(){
var key = $(this).text();
var value = $(this).next().text();
console.log(key + "=" + value);
//here i want to create array of objects instead of normal array
//and push both key and value to array of object
MyArray.push(key);
});
</code></pre>
<p>Object array sample that i want construct:</p>
<pre><code>var myArray = [{
id: 1,
name: 'fruits',
category: 'US Fruits',
categoryIcon: 'http://www.somsite.com/categories/1.jpg',
country: 'US'
}, {
id: 2,
name: 'Vegetable',
category: 'Eu Vegetable',
categoryIcon: 'http://www.somsite.com/categories/2.jpg',
country: 'EU'
}, ];
</code></pre>
<p>edit:
I tried to print the array of objects like this but i got undefined for all
values!:</p>
<pre><code>$.each(MyArray,function(j, object){
var div = "<tr id=\""+j+"\">\n" +
"<td>"+j+"</td>\n" +
"<td><img src=\""+ object.categoryIcon +"\" height=\"42\" width=\"42\"></td>\n" +
"<td>\n" +
"<a href=\"javascript:doit('id=" + object.id + "&name=" + object.name + "&category=" + object.category + "&categoryIcon=" + object.categoryIcon + "','"+ object.country +"')\" onclick=\"selectLink(this);\">" + object.name + "</a><br> \n" +
"<br></td></tr>\n\n";
$("#myDiv").append(div);
});
</code></pre>
| <p>If you just replace </p>
<pre><code>MyArray.push(key);
</code></pre>
<p>with </p>
<pre><code>var o = {};
o[key] = value;
MyArray.push(o);
</code></pre>
<p>It would do that, but you seem to want to iterate over each <code>dict</code>, and then get the value of each <code>key</code> inside the parent <code>dict</code> etc.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var xml = '<?xml version="1.0" encoding="UTF-8"?> <dict><key>ItemLists</key> <array><dict><key>id</key> <string>1</string> <key>name</key> <string>fruits</string> <key>category</key> <string>US Fruits</string> <key>categoryIcon</key> <string>http://www.somsite.com/categories/1.jpg</string> <key>country</key> <string>US</string> </dict> <dict><key>id</key> <string>2</string> <key>name</key> <string>Vegetable</string> <key>category</key> <string>Eu Vegetable</string> <key>categoryIcon</key> <string>http://www.somsite.com/categories/2.jpg</string> <key>country</key> <string>EU</string> </dict> </array> </dict>';
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
var MyArray = [];
$(xml).find("array dict").each(function(_,elem) {
var o = {};
$('key', elem).each(function() {
var key = $(this).text();
var value = $(this).next().text();
o[key] = value;
});
MyArray.push(o);
});
console.log(MyArray)</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {top:0; min-height:100%!important}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<p>Alternativetely, you could use <code>map()</code> and <code>reduce()</code></p>
<pre><code>var MyArray = $(xml).find("array dict").map(function(_,elem) {
return $('key', elem).toArray().reduce(function(a,b) {
return a[$(b).text()] = $(b).next().text(), a;
}, {});
}).get();
</code></pre>
|
Angular2 - Display image <p>I created a Angular2 app that allows the user to upload images. I want to implement a preview option. However, when i try to imperilment it the image doesn't show up. How do i achieve this feature? </p>
<p>UploadComponent.ts</p>
<pre><code>import * as ng from '@angular/core';
//import { UPLOAD_DIRECTIVES } from 'ng2-uploader';
import {UploadService} from '../services/upload.service';
@ng.Component({
selector: 'my-upload',
providers:[UploadService],
template: require('./upload.html')
})
export class UploadComponent {
progress:any;
logo:any;
filesToUpload: Array<File>;
constructor(public us:UploadService){
this.filesToUpload = [];
}
upload() {
this.us.makeFileRequest("http://localhost:5000/api/SampleData/Upload", this.filesToUpload)
.then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}
onFileChange(fileInput: any){
this.logo = fileInput.target.files[0];
}
}
</code></pre>
<p>Upload.html </p>
<pre><code><h2>Upload</h2>
<input type="file" (change)="onFileChange($event)" placeholder="Upload image..." />
<button type="button" (click)="upload()">Upload</button>
<img [src]="logo" alt="Preivew">
</code></pre>
| <p>The way you try it, you don't get the image URL with <code>fileInput.target.files[0]</code>, but an object.</p>
<p>To get an image URL, you can use <code>FileReader</code> (<a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader" rel="nofollow">documentation here</a>)</p>
<pre><code>onFileChange(fileInput: any){
this.logo = fileInput.target.files[0];
let reader = new FileReader();
reader.onload = (e: any) => {
this.logo = e.target.result;
}
reader.readAsDataURL(fileInput.target.files[0]);
}
</code></pre>
|
VideoJS Swf Remove Right Click Menu <p>i want disabling context menu , i never worked with actionscript , after some search i find this code for disabling context menu :</p>
<pre><code>stage.addEventListener(MouseEvent.RIGHT_CLICK, function(e:MouseEvent):void {});
stage.addEventListener(MouseEvent.CONTEXT_MENU, function(e:MouseEvent):void {});
Mouse.hide();
</code></pre>
<p>i want know how can apply it in VideoJS.as.</p>
<p>Here is source code in ActionScript <a href="https://github.com/videojs/video-js-swf/tree/master/src" rel="nofollow">https://github.com/videojs/video-js-swf/tree/master/src</a></p>
| <blockquote>
<p><em>"I find this code for disabling context menu... I want know how can apply it in <code>VideoJS.as</code>"</em>.</p>
</blockquote>
<p>Open <a href="https://github.com/videojs/video-js-swf/blob/master/src/VideoJS.as" rel="nofollow"><strong><code>VideoJS.as</code></strong></a>... Find the following code (line 57 onwards):</p>
<blockquote>
<pre><code> // add content-menu version info
var _ctxVersion:ContextMenuItem = new ContextMenuItem("VideoJS Flash Component v" + VERSION, false, false);
var _ctxAbout:ContextMenuItem = new ContextMenuItem("Copyright © 2014 Brightcove, Inc.", false, false);
var _ctxMenu:ContextMenu = new ContextMenu();
_ctxMenu.hideBuiltInItems();
_ctxMenu.customItems.push(_ctxVersion, _ctxAbout);
this.contextMenu = _ctxMenu;
</code></pre>
</blockquote>
<p><br>
Change it to become</p>
<pre><code>// add content-menu version info
/*
var _ctxVersion:ContextMenuItem = new ContextMenuItem("VideoJS Flash Component v" + VERSION, false, false);
var _ctxAbout:ContextMenuItem = new ContextMenuItem("Copyright © 2014 Brightcove, Inc.", false, false);
var _ctxMenu:ContextMenu = new ContextMenu();
_ctxMenu.hideBuiltInItems();
_ctxMenu.customItems.push(_ctxVersion, _ctxAbout);
this.contextMenu = _ctxMenu;
*/
this.addEventListener(MouseEvent.RIGHT_CLICK, function(e:MouseEvent):void {});
this.addEventListener(MouseEvent.CONTEXT_MENU, function(e:MouseEvent):void {});
</code></pre>
<p>Now try compiling a new SWF output of VideoJS. If it worked correctly there should be no response when right-clicking. Above code is untested (no time) but it's the correct code logic. </p>
<p>Let me know if it's a working solution.</p>
|
Robolectric different threads in Android Studio vs. Gradle tests <p>why are thread names different when I start a Robolectric test from Android Studio vs. the Gradle build?</p>
<p>e.g. consider this simple test:</p>
<pre><code>@RunWith(RobolectricTestRunner.class)
public class RobolectricRxThreadTest {
@Test
public void testMainThreadName() {
assertEquals("main", Thread.currentThread().getName());
}
}
</code></pre>
<p>when I start this test</p>
<ul>
<li>directly in <strong>Android Studio</strong> (by pressing <kbd>CTRL</kbd>+<kbd>SHIFT</kbd>+<kbd>F10</kbd>) the test is <strong>okay</strong></li>
<li>but when I start the <strong>gradle tests</strong> (e.g. from the Gradle projects view: <code>:app</code> - <code>Tasks</code> - <code>verification</code> - <code>test</code>, or from the Terminal view: <code>./gradlew test</code>) it <strong>fails</strong>.<br>
The thread name is <code>Thread worker</code> and not <code>main</code> as expected.</li>
</ul>
| <p>I just reproduced the issue, but I wonder why do you need this test?</p>
<p>If you really want to check main thread then the correct way would be:</p>
<pre><code> assertThat(Thread.currentThread()).isEqualTo(Looper.getMainLooper().getThread());
</code></pre>
<p>And this test pass from AS and console both runs.</p>
|
chrome extension native message not received in c# app <p>I am trying to communicate between chrome extension and c# app using native messaging. I have refered the link
<a href="https://developer.chrome.com/extensions/nativeMessaging" rel="nofollow">nativeMessaging</a></p>
<p>In my extension there are 2 menu buttons, one for connectnative and other is postmessage.</p>
<p>When I click on connect native my c# host app(app.exe) gets launched. But after clicking on postmessage no message is received in app.exe.</p>
<p>Below are sample codes</p>
<p>com.ln.json</p>
<pre><code>{
"name": "com.ln",
"description": "Chrome Native Messaging API Example Host",
"path": "app.bat",
"type": "stdio",
"allowed_origins":
[
"chrome-extension://hplkgmmknmccnfalidkjhkponfakmhag/"
]
}
</code></pre>
<p>menupopup.js</p>
<pre><code>var port=null;
chrome.browserAction.onClicked.addListener(LinguifyOnClick());
function MenuButtonClicked(evnt)
{
try
{
var menuId = evnt.target.id;
if(menuId == "0")
{
Communicate();
}
if(menuId == "1")
{
SendPostMessage();
}
window.close();
}
catch(err)
{
}
}
function LinguifyOnClick()
{
try
{
//var BodyTag = document.getElementsByTagName("body");
var DefaultTag = document.getElementById("DefaultUl");
for (iCtr = 0; iCtr<3; iCtr++)
{
var tmpTag = document.createElement("li");
tmpTag.id = iCtr.toString();
tmpTag.className = iCtr.toString();
if(iCtr==0)
{
tmpTag.innerHTML = " ConnectToNativeHost";
}
else if(iCtr==1)
{
tmpTag.innerHTML = " SendPostMessage";
}
DefaultTag.appendChild(tmpTag);
tmpTag.addEventListener('click', MenuButtonClicked);
}
}
catch(err)
{
}
}
function SendPostMessage()
{
var message = {"text" : "PostMessageSent_EXT"};
alert("SendPostMessage=" + port + JSON.stringify(message));
port.postMessage(message);
alert("SendPostMessage=" + JSON.stringify(message));
}
function Communicate()
{
port = chrome.runtime.connectNative('com.ln');
//port = chrome.extension.connectNative('com.ln');
port.onMessage.addListener(function(msg)
{
alert("Received from native app:1 =" + msg);
});
port.onDisconnect.addListener(function()
{
alert("Disconnected");
});
}
</code></pre>
<p>app.exe(c# code)</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace sign
{
class Program
{
public static void Main(string[] args)
{
JObject data;
while ((data = Read()) != null)
{
var processed = ProcessMessage(data);
Write(processed);
if (processed == "exit")
{
return;
}
}
}
public static string ProcessMessage(JObject data)
{
try
{
var message = data["message"].Value<string>();
switch (message)
{
case "test":
return "testing!";
case "exit":
return "exit";
default:
return "echo: " + message;
}
}
catch (Exception ex)
{
Console.Write("ProcessMessage =" + ex.Message);
}
return " ";
}
public static JObject Read()
{
try
{
var stdin = Console.OpenStandardInput();
var length = 0;
var lengthBytes = new byte[4];
stdin.Read(lengthBytes, 0, 4);
length = BitConverter.ToInt32(lengthBytes, 0);
var buffer = new char[length];
using (var reader = new StreamReader(stdin))
{
while (reader.Peek() >= 0)
{
reader.Read(buffer, 0, buffer.Length);
}
}
return (JObject)JsonConvert.DeserializeObject<JObject>(new string(buffer));
}
catch (Exception ex)
{
Console.Write("Read =" + ex.Message);
}
return null;
}
public static void Write(JToken data)
{
try
{
var json = new JObject();
json["data"] = data;
var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToString(Formatting.None));
var stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((bytes.Length >> 0) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 8) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 16) & 0xFF));
stdout.WriteByte((byte)((bytes.Length >> 24) & 0xFF));
stdout.Write(bytes, 0, bytes.Length);
stdout.Flush();
}
catch (Exception ex)
{
Console.Write("Write =" + ex.Message);
}
}
}
}
</code></pre>
| <p>I am able to communicate now. What I changed is</p>
<ol>
<li>Created windows form app as native app, previously it was console app. Don't know why but extension could not communicate with console app.
<ol start="2">
<li>Instead of running .bat from json run direct native app.</li>
</ol></li>
</ol>
|
database "db/development.sqlite3" does not exist - how to fix? <p>a friend deployed my application on Heroku, and it works fine there. But I can not open my application on local server. Can anyone help? </p>
<p>When going on localhost i get the following error message: </p>
<p>ActiveRecord::NoDatabaseError
FATAL: database "db/development.sqlite3" does not exist</p>
<p>Extracted source (around line #661):</p>
<pre><code> rescue ::PG::Error => error
if error.message.include?("does not exist")
raise ActiveRecord::NoDatabaseError.new(error.message, error)
else
raise
end
</code></pre>
| <p>Update your <code>database.yml</code></p>
<pre><code>default: &default
adapter: postgresql
encoding: utf8
development:
<<: *default
database: your_app_development
username: your_usernmae
password: your_password
</code></pre>
|
Why is a switch case statement unable to work with properties of an Enum? <p>I am writing a simple game in which I use an Enum, <code>CommandManager</code>, to store information about the possible commands and what each one does. The main purposes of this Enum is to be able to print out a menu of available commands, as well as being used to check input and performing the action related to that input. My problem lies with that second use, where I am using a switch statement to determine what the user wants to do based on their input. I'm getting a compilation error when trying to use a property of an Enum (via a getter method) as a case label. The error message provided is that <code>case expressions must be constant expressions</code>. Given that the properties of <code>CommandManager</code> are declared to be final, am I right in thinking that properties of Enums simply cannot be used in switch statements? If this is the case, why?</p>
<p>Simplified version of the code included below in case it's an error on my end.</p>
<p>Method Code:</p>
<pre><code>void interpretInput() {
String command = input.getInput();
if (command.length() == 2) {
switch (command) {
case CommandManager.MAINMENU.getCommand(): goToMainMenu();
break;
case CommandManager.NEWGAME.getCommand(): startNewGame();
break;
case CommandManager.LISTGAMES.getCommand(): listSavedGames();
break;
case CommandManager.EXITGAME.getCommand(): exitGame();
break;
case CommandManager.HELPMENU.getCommand(): listAllCommands();
break;
}
}
}
</code></pre>
<p>Enum code:</p>
<pre><code>public enum CommandManager {
NEWGAME("!n", "New game"),
MAINMENU("!m", "Go to main menu"),
EXITGAME("!q", "Exit Battleships"),
LISTGAMES("!g", "List saved games"),
HELPMENU("!h", "Open help menu"),
LOADGAME("!l", "Load a new game"),
SAVEGAME("!s", "Save current game");
private final String command;
private final String menuOption;
CommandManager(String aCommand, String anOption) {
command = aCommand;
menuOption = anOption;
}
String getCommand() {
return command;
}
String getMenuOption() {
return menuOption;
}
}
</code></pre>
| <blockquote>
<p>Am I right in thinking that properties of Enums simply cannot be used in switch statements? </p>
</blockquote>
<p>You are.</p>
<blockquote>
<p>If this is the case, why?</p>
</blockquote>
<p>Because the "labels" for a switch statement need to be <em>compile time</em> constants, and the properties of an <code>enum</code> do not qualify.</p>
<p>The reason that they need to be compile time constants is that the compiler needs to check that the switch labels are distinct. It cannot allow something like this</p>
<pre><code>switch (someValue) {
case A: doA();
case B: doB();
}
</code></pre>
<p>where <code>A</code> and <code>B</code> turn out to have the same value. If <code>A</code> and <code>B</code> are not compile-time constants, then the compiler cannot detect the problem.</p>
|
How to ignore folder in GitHub correctly? <p>In my <code>.gitignore</code> file I added a path to folder I don't want to see in GitHub website:</p>
<pre><code>Results/.ipynb_checkpoints/
</code></pre>
<p>Then I push this changes:</p>
<pre><code>git commit -a -m "add ignore"
git push origin master
</code></pre>
<p>But when I go to site, I still see this folder. How to do it correctly?</p>
| <p>You need to remove the folder now that it is in the .gitignore. You can do this by deleting the folder locally, adding changes, commit it and then push it. If you need the folder in your local repository you can then recover it by making a backup, before deleting it. </p>
<p>If you however do not want to remove the folder locally, and delete it <strong>just from the remote</strong>, you can do:</p>
<pre><code>git rm -r --cached Results/.ipynb_checkpoints/
git commit -m "Removed folder from repository"
git push origin master
</code></pre>
<p>More about deleting a file/folder from the remote repository but <strong>not</strong> locally can be read in <a href="http://stackoverflow.com/questions/6313126/how-to-remove-a-directory-in-my-github-repository">this question and answers</a>.</p>
|
how to check in a pandas DataFrame entry exists by (index, column) <p>I have searched and searched but I can't find how to test whether a pandas data frame entry exists by (index, column).</p>
<p>for example:</p>
<pre><code>import pandas
df = pandas.DataFrame()
df.ix['apple', 'banana'] = 0.1
df.ix['apple', 'orange'] = 0.1
df.ix['kiwi', 'banana'] = 0.2
df.ix['kiwi', 'orange'] = 0.7
df
banana orange
apple 0.1 0.1
kiwi 0.2 0.7
</code></pre>
<p>Now I want to test whether an entry exists</p>
<pre><code>if (["apple", "banana"] in df)
</code></pre>
<p>.. should be <strong>True</strong></p>
<p>and </p>
<pre><code>if (["apple", "apple"] in df)
</code></pre>
<p>.. should be <strong>False</strong></p>
<hr>
<p>Actually the reason I'm testing for existence is because the following doesn't work</p>
<pre><code>some loop ..
df[wp] += some_value
pass
</code></pre>
<p>It fails when df[wp] doesn't exist. This does work if the expression is</p>
<pre><code>some loop ..
df[wp] += some_value
pass
</code></pre>
<p>because pandas does have the idea of extending an array through assignment.</p>
| <p>You can check for the existence in index and columns:</p>
<pre><code>('kiwi' in df.index) and ('apple' in df.columns)
</code></pre>
<p>Or you can use a try/except block:</p>
<pre><code>try:
df.ix['kiwi', 'apple'] += some_value
except KeyError:
df.ix['kiwi', 'apple'] = some_value
</code></pre>
<p>Note that DataFrames' shapes are not meant to be dynamic. This may slow down your operations heavily. So it might be better to do these things with dictionaries and finally turn them into DataFrames.</p>
|
delete an array element in MATLAB <p>In MATLAB, we can delete an object by</p>
<pre><code>o = obj();
delete o;
</code></pre>
<p>Can we explicitly delete an object in an array?</p>
<pre><code>arr = {obj(), obj(), obj()};
delete arr{1}; % ???
</code></pre>
<p>Also, does MATLAB release the memory if we call delete explicitly?</p>
| <p>First off, this line</p>
<pre><code>delete o;
</code></pre>
<p>does not do what you think it does. In <em>command syntax</em>, o is interpreted as a string, and this will delete a file named "o" in your current working directory.</p>
<p>If you want to delete the object <code>o</code> then you need to use <em>functional syntax</em>, i.e.</p>
<pre><code>delete(o); % where o is an object in the workspace.
</code></pre>
<p>However, this does not do what you think it does either!
"Deleting" destroys an object referenced by a <em>handle</em>, i.e. <strong>graphics object handles</strong> (like plots) or <strong>matlab objects inheriting from the <em>handle</em> superclass</strong>. Note that the "handle" variable <code>o</code> itself is still on your workspace, and it points to a now deleted object!</p>
<p>If what you have is simply a normal variable / object and you just want to remove it from the workspace, you just <code>clear</code> it instead.</p>
<p>Secondly, arr is not an 'array', it's a cell array. This is a bit of a pedantic point, but an important one, since matlab <em>does</em> allow normal arrays of objects.</p>
<p>Thirdly, yes, to answer your question, there is a way to explicitly delete / remove an object in an array, such that the array is spliced back together. The way to do this is by assigning as an element of that array an empty element, i.e.</p>
<pre><code>arr = {obj(), obj(), obj()};
arr(1) = [];
</code></pre>
<p>matlab's garbage collector takes care of things under the hood, you do not need to explicitly handle memory in this sense.
<hr>
PS. All the above also apply to octave.</p>
|
flashdata codeigniter with array <p>I have problem with array on flashdata codeigniter to send alert, if without framework this code work correcly, I modified this to codeigniter, but it does not work.</p>
<p>Controller Code:</p>
<pre><code> function reply(){
$id = $this->input->post('id');
$err = array();
if(!$_POST['msg']) {
$err[] = 'all the fields must be filled in!';
}
else if(!count($err)){
$data = array(
'DestinationNumber'=> $this->input->post('hp'),
'TextDecoded'=> $this->input->post('msg'),
'i_id'=> $this->input->post('id'));
$this->inbox_model->reply($data);
if($data >= 1) {
$this->session->set_flashdata['msg']['success']='Send Success!';
}
else {
$err[] = 'Send Failed!';
}
}
if(count($err)){
$this->session->set_flashdata['msg']['err'] = implode('<br />',$err);
}
redirect('sms/inbox/read/'.$id);
}
</code></pre>
<p>View Code :</p>
<pre><code>if($this->session->flashdata['msg']['err']){
echo "<div class='alert alert-danger alert-dismissible'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>
".$this->session->flashdata['msg']['err']."</div>";
$this->session->unset_flashdata['msg']['err'];
}
if($this->session->flashdata['msg']['success']){
echo "<div class='alert alert-success alert-dismissible'>
<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>
".$this->session->flashdata['msg']['success']."</div>";
$this->session->unset_flashdata['msg']['success'];
}
</code></pre>
<p>Who can help me?</p>
| <p>you could set array to flashdata session using the simple way</p>
<pre><code>$array_msg = array('first'=>'<p>msg 1</p>','second'=>'<p>msg2</p>');
</code></pre>
<p>then pass it to session</p>
<pre><code>$this->session->set_flashdata('msg',$array_msg);
</code></pre>
<p>then access it </p>
<pre><code>$msg = $this->session->flashdata('msh');
echo $msg['first'];
</code></pre>
|
Tomcat runs in Eclipse but can't do a GET request <p>I created just a dynamic web project in Eclipse and when I run the the helloworld webapp then I see the index.html page with no problems screenshot:
<a href="http://i.stack.imgur.com/2tYQb.png" rel="nofollow"><img src="http://i.stack.imgur.com/2tYQb.png" alt="enter image description here"></a></p>
<p>But when I go to the <code>/HelloServlet</code> path then I'm getting a 404 error screenshot:
<a href="http://i.stack.imgur.com/DGfr6.png" rel="nofollow"><img src="http://i.stack.imgur.com/DGfr6.png" alt="enter image description here"></a></p>
<p>However when I go to localhost:8080 then I can see that Tomcat is running screenshot:
<a href="http://i.stack.imgur.com/DL6mr.png" rel="nofollow"><img src="http://i.stack.imgur.com/DL6mr.png" alt="enter image description here"></a></p>
<p>In the logs I can also read that the server is running screenshot:
<a href="http://i.stack.imgur.com/8A8gf.png" rel="nofollow"><img src="http://i.stack.imgur.com/8A8gf.png" alt="enter image description here"></a></p>
<p>Here are my server properties screenshot:
<a href="http://i.stack.imgur.com/f2Q1c.png" rel="nofollow"><img src="http://i.stack.imgur.com/f2Q1c.png" alt="enter image description here"></a></p>
<p>And here is the code of HelloServlet.java:</p>
<pre><code>@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public HelloServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
</code></pre>
<p>Anyone has a clue how to fix this? At my work I had installed and configured Eclipse with Tomcat with no problems. But somehow I can't manage to get it working at home.</p>
| <p>Change the line of code has annotation <code>@WebServlet</code> become to:</p>
<pre><code>@WebServlet(name = "HelloServlet", urlPatterns = "/HelloServlet")
</code></pre>
<p>You will be happy.</p>
<p>To avoid exception (When application context is <code>/</code>), you should check <code>request.getContextPath()</code>.</p>
<pre><code>import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "HelloServlet", urlPatterns = "/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getContextPath().length() > 0) {
response.getWriter().append("Served at: ").append(request.getContextPath());
} else {
response.getWriter().append("Served at: " + "/");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
</code></pre>
|
Modify/flatten result from sql one to many query with multiple joins <p>Consider the following simplified schema example -</p>
<pre><code>sys_systems
id name
---------------------
1 Inventory
sys_shadow_data
id primary_key_value sys_schema_id field_value
---------------------------------------------------------
1 1 143 Awaiting audit
2 1 144 90
sys_schemas
id field_name
-------------------
143 notes
144 status
</code></pre>
<p>The following query -</p>
<pre><code>select sys_systems.*,
(select sys_shadow_data.field_value where sys_schemas.field_name = 'status') as status,
(select sys_shadow_data.field_value where sys_schemas.field_name = 'notes') as notes
from sys_systems
left join sys_shadow_data
on sys_systems.id = sys_shadow_data.primary_key_value
left join sys_schemas
on sys_schemas.id = sys_shadow_data.sys_schema_id
</code></pre>
<p>yields -</p>
<pre><code>id name status notes
-----------------------------------------
1 Inventory 90 null
1 Inventory null Awaiting audit
</code></pre>
<p>The result I would like to obtain is -</p>
<pre><code>id name status notes
-----------------------------------------
1 Inventory 90 Awaiting audit
</code></pre>
<p>Is there a change I can make to the sql query to achieve this or is this a case whereby I would need to process the results in the application code?</p>
| <p>Your query amounts to pivoting the joined tables on the <code>field_name</code> column from the <code>sys_schemas</code> table to generate new columns for each value in that column. You can <code>GROUP BY</code> the inventory ID and name, then use <code>MAX</code> to collapse the two records into one:</p>
<pre><code>SELECT sys_systems.id,
sys_systems.name,
MAX(CASE WHEN sys_schemas.field_name = 'status'
THEN sys_shadow_data.field_value ELSE NULL END) AS status,
MAX(CASE WHEN sys_schemas.field_name = 'notes'
THEN sys_shadow_data.field_value ELSE NULL END) AS notes
FROM sys_systems
LEFT JOIN sys_shadow_data
ON sys_systems.id = sys_shadow_data.primary_key_value
LEFT JOIN sys_schemas
ON sys_schemas.id = sys_shadow_data.sys_schema_id
GROUP BY sys_systems.id,
sys_systems.name
</code></pre>
|
To find distance between two letters <p>In this question,it is required to find the distance between two letters
for eg. Between A and E,the letters are B,C,D.So,distance between the letters is number of letters+1 ie,4 here.But I'm not getting the output for this code </p>
<pre><code> import java.util.*;
public class Main{
public static void main(String args[]){
String s1,s2;
Scanner input=new Scanner(System.in);
input.nextLine();
s1=input.nextLine();
input.nextLine();
s2=input.nextLine();
int result=((int)s2.toLowerCase().charAt(0)-(int)s1.toLowerCase().charAt(0))+1;
result=Math.abs(result);
System.out.println(result);
}
}
</code></pre>
| <p>You have extra nextLine method calls. Modified your code to make it working.</p>
<pre><code>import java.util.Scanner;
public class LetterDistance {
public static void main(String[] args) {
String s1, s2;
Scanner input = new Scanner(System.in);
s1 = input.nextLine();
s2 = input.nextLine();
int result = ((int) s2.toLowerCase().charAt(0) - (int) s1.toLowerCase()
.charAt(0)) + 1;
result = Math.abs(result);
System.out.println(result);
}
}
</code></pre>
|
Separate package names for iOS and Android <p>I currently have a native app published to the App Store and Google Play and both have different package names. I was wanting to know if there is there a way to tell NativeScript to use a one package name for iOS and a different one for Android? Thank you.</p>
| <p>Yep, you can absolutely do that. For iOS, include a <code>CFBundleIdentifier</code> flag in your <code>app/App_Resources/iOS/Info.plist</code> file.</p>
<pre><code><key>CFBundleIdentifier</key>
<string>com.mycompany.myapp</string>
</code></pre>
<p>And for Android, update the <code>android.defaultConfig.applicationId</code> in your <code>app/App_Resources/Android/app.gradle</code> file. See <a href="https://github.com/NativeScript/template-hello-world/blob/90b81bcb772ab21a06f06bd502be2043e6afc9ee/App_Resources/Android/app.gradle#L11" rel="nofollow">https://github.com/NativeScript/template-hello-world/blob/90b81bcb772ab21a06f06bd502be2043e6afc9ee/App_Resources/Android/app.gradle#L11</a>.</p>
|
MYSQL / Spring Hibernate: Connection has already been closed <p>So, I want to do 32 write operations under one @Transactional. I have set maxActive connections as "100", maxIdle as "50" (which I believe are quite high), maxTimeout is set to 150000 and removeAbandonedTimeout = 3000</p>
<p>Here's the tomcat configuration:</p>
<pre><code>driverClassName="com.mysql.jdbc.Driver" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" testWhileIdle="true" validationQuery="SELECT 1" validationInterval="30000" timeBetweenEvictionRunsMillis="30000" removeAbandoned="true" removeAbandonedTimeout="3000" url="jdbc:mysql://127.0.0.1:3306/cas?autoReconnect=true"/>
</code></pre>
<p>Here's java code:</p>
<pre><code>@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, timeout = 3600)
public void updateDBFromMap(String clientCode, String date, String time, EClientParameterMaintenance ebtData) throws Exception {
if (ebtData.getCity() != null && !ebtData.getCity().isEmpty()) {
String tableName;
try {
tableName = maintenanceService.getDailyTableName(clientCode, date, EventBifurcationType.CITY);
for (String cityKey : ebtData.getCity().keySet()) {
dailyFlushDao.updateCity(ebtData.getCity().get(cityKey), tableName, time);
}
} catch (Exception e) {
LOG.error("Exception:", e);
throw e;
}
} .... and 31 more such update operations
</code></pre>
<p>And here's the error:</p>
<pre><code>- Connection has already been closed.
19:50:56,162 ERROR [FlushServiceImpl] - Exception:
org.springframework.orm.hibernate4.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [INSERT INTO fc_p_faclntlms1aoqglwzza0a_20161001 (time_period, prediction_count, footfall_count, unique_footfall_count, time_spent, fence_category_id, property_code, created) VALUES ('1900','2','2','2','60','19','FAPORYLMS1AOMXHHD3K4B',now()) ON DUPLICATE KEY UPDATE prediction_count=prediction_count+2, footfall_count=footfall_count+2,unique_footfall_count=unique_footfall_count+2,time_spent=time_spent+60;]; SQL state [null]; error code [0]; could not prepare statement; nested exception is org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:170)
at org.springframework.orm.hibernate4.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:57)
at org.springframework.orm.hibernate4.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:44)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
at com.focus.cas.service.aspect.CASAspectHandler.logMethodExecutionTime(CASAspectHandler.java:122)
at com.focus.cas.service.aspect.CASAspectHandler.profile(CASAspectHandler.java:43)
at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.focus.cas.dbaccess.mysql.flush.impl.DailyFlushDaoImpl$$EnhancerBySpringCGLIB$$1a5b5f55.updateFenceCategoryProperty(<generated>)
at com.focus.cas.service.flush.impl.FlushServiceImpl.updateDBFromMap(FlushServiceImpl.java:1314)
at com.focus.cas.service.flush.impl.FlushServiceImpl$$FastClassBySpringCGLIB$$d877b180.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.focus.cas.service.flush.impl.FlushServiceImpl$$EnhancerBySpringCGLIB$$f652020f.updateDBFromMap(<generated>)
at com.focus.cas.service.flush.impl.FlushServiceImpl.flush(FlushServiceImpl.java:1046)
at com.focus.cas.service.flush.impl.FlushServiceImpl.access$100(FlushServiceImpl.java:107)
at com.focus.cas.service.flush.impl.FlushServiceImpl$FlushThread.run(FlushServiceImpl.java:1534)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:196)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:96)
at org.hibernate.engine.query.spi.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:205)
at org.hibernate.internal.SessionImpl.executeNativeUpdate(SessionImpl.java:1310)
at org.hibernate.internal.SQLQueryImpl.executeUpdate(SQLQueryImpl.java:389)
at com.focus.cas.dbaccess.mysql.flush.impl.DailyFlushDaoImpl.updateFenceCategoryProperty(DailyFlushDaoImpl.java:269)
at com.focus.cas.dbaccess.mysql.flush.impl.DailyFlushDaoImpl$$FastClassBySpringCGLIB$$f7b6a91f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 30 more
Caused by: java.sql.SQLException: Connection has already been closed.
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:117)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:109)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:80)
at com.sun.proxy.$Proxy33.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$1.doPrepare(StatementPreparerImpl.java:103)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
... 40 more
19:50:56,717 ERROR [TransactionInterceptor] - Application exception overridden by rollback exception
org.springframework.orm.hibernate4.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [INSERT INTO fc_p_faclntlms1aoqglwzza0a_20161001 (time_period, prediction_count, footfall_count, unique_footfall_count, time_spent, fence_category_id, property_code, created) VALUES ('1900','2','2','2','60','19','FAPORYLMS1AOMXHHD3K4B',now()) ON DUPLICATE KEY UPDATE prediction_count=prediction_count+2, footfall_count=footfall_count+2,unique_footfall_count=unique_footfall_count+2,time_spent=time_spent+60;]; SQL state [null]; error code [0]; could not prepare statement; nested exception is org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:170)
at org.springframework.orm.hibernate4.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:57)
at org.springframework.orm.hibernate4.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:44)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
at com.focus.cas.service.aspect.CASAspectHandler.logMethodExecutionTime(CASAspectHandler.java:122)
at com.focus.cas.service.aspect.CASAspectHandler.profile(CASAspectHandler.java:43)
at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.focus.cas.dbaccess.mysql.flush.impl.DailyFlushDaoImpl$$EnhancerBySpringCGLIB$$1a5b5f55.updateFenceCategoryProperty(<generated>)
at com.focus.cas.service.flush.impl.FlushServiceImpl.updateDBFromMap(FlushServiceImpl.java:1314)
at com.focus.cas.service.flush.impl.FlushServiceImpl$$FastClassBySpringCGLIB$$d877b180.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:267)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.focus.cas.service.flush.impl.FlushServiceImpl$$EnhancerBySpringCGLIB$$f652020f.updateDBFromMap(<generated>)
at com.focus.cas.service.flush.impl.FlushServiceImpl.flush(FlushServiceImpl.java:1046)
at com.focus.cas.service.flush.impl.FlushServiceImpl.access$100(FlushServiceImpl.java:107)
at com.focus.cas.service.flush.impl.FlushServiceImpl$FlushThread.run(FlushServiceImpl.java:1534)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:196)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:96)
at org.hibernate.engine.query.spi.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:205)
at org.hibernate.internal.SessionImpl.executeNativeUpdate(SessionImpl.java:1310)
at org.hibernate.internal.SQLQueryImpl.executeUpdate(SQLQueryImpl.java:389)
at com.focus.cas.dbaccess.mysql.flush.impl.DailyFlushDaoImpl.updateFenceCategoryProperty(DailyFlushDaoImpl.java:269)
at com.focus.cas.dbaccess.mysql.flush.impl.DailyFlushDaoImpl$$FastClassBySpringCGLIB$$f7b6a91f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
</code></pre>
<p>Fighting over it for the last 7 days. Almost all solutions have failed in my case.</p>
| <p>The setting you used has removeAbandonedTimeout set to 3 sec. Looking for the documentation for <strong>org.apache.tomcat.jdbc.pool.DataSourceFactory</strong> which you are using at <a href="https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html" rel="nofollow">https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html</a> , this property should be set to the longest running query your applications might have. From the docs,</p>
<blockquote>
<blockquote>
<p>removeAbandoned<br>
(boolean) Flag to remove abandoned connections if they exceed the removeAbandonedTimeout. If set to true a connection is considered abandoned and eligible for removal if it has been in use longer than the removeAbandonedTimeout Setting this to true can recover db connections from applications that fail to close a connection. See also logAbandoned The default value is false.</p>
<p>removeAbandonedTimeout<br>
(int) Timeout in seconds before an abandoned(in use) connection can be removed. The default value is 60 (60 seconds). The value should be set to the longest running query your applications might have.</p>
</blockquote>
</blockquote>
<p>Thus you should check for the maximum time any query used by your application is taking and set this accordingly.</p>
|
STM32F4 PWM and interrupt with the same timer <p>I have a STM32F407x. Is it possible to have a PWM Signal on a Pin and at the same time getting a timer interrupt if the UPPER value is reached? I tried the following code, but I only get once an interrupt (count stays at 1 forever if I use the debugger), but the PWM Signal is still available at PB6:</p>
<pre><code>volatile int count=0;
void TM_LEDS_Init(void) {
GPIO_InitTypeDef GPIO_InitStruct;
/* Clock for GPIOB */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
/* Alternating functions for pins */
GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_TIM4);
/* Set pins */
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void TM_TIMER_Init(void) {
TIM_TimeBaseInitTypeDef TIM_BaseStruct;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
TIM_BaseStruct.TIM_Prescaler = 100;
TIM_BaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_BaseStruct.TIM_Period = 256;
TIM_BaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_BaseStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM4, &TIM_BaseStruct);
}
void TM_PWM_Init(void) {
TIM_OCInitTypeDef TIM_OCStruct;
TIM_OCStruct.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCStruct.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCStruct.TIM_Pulse = 150; /* 25% duty cycle */
TIM_OC1Init(TIM4, &TIM_OCStruct);
TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);
/* Clear Interrupt */
for(int i=0; i<3; i++)
if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
/* Enable Interrupt */
TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM4, ENABLE);
}
void configNVIC(void)
{
NVIC_InitTypeDef initNVICStruct;
/* Enable the TIM2 global Interrupt */
initNVICStruct.NVIC_IRQChannel = TIM4_IRQn;
initNVICStruct.NVIC_IRQChannelPreemptionPriority = 1;
initNVICStruct.NVIC_IRQChannelSubPriority = 3;
initNVICStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&initNVICStruct);
}
void TIM4_IRQHandler(void) //This Interrupt changes changes state from x to x+-1
{
if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
count++;
}
}
int main(void) {
/* Initialize system */
SystemInit();
configNVIC();
/* Init leds */
TM_LEDS_Init();
/* Init timer */
TM_TIMER_Init();
/* Init PWM */
TM_PWM_Init();
int i=0;
while (1) {
i=count;
}
}
</code></pre>
| <p>If you're trying to count pulses or stop at a certain pulse this post may help</p>
<p><a href="https://my.st.com/public/STe2ecommunities/mcu/Lists/cortex_mx_stm32/Flat.aspx?RootFolder=%2Fpublic%2FSTe2ecommunities%2Fmcu%2FLists%2Fcortex_mx_stm32%2FStop%20PWM%20output%20after%20N%20steps&FolderCTID=0x01200200770978C69A1141439FE559EB459D7580009C4E14902C3CDE46A77F0FFD06506F5B&currentviews=4346" rel="nofollow">Stop PWM output after N steps</a></p>
|
Datagrid context menu only for single select <p>I have a datagrid with context menu. How prevent context menu showing for multiple selection? I tried to add attached property but got an error <strong>The attachable property 'ContextMenuVisibilityMode' was not found in type 'ProcessIntasnceActivitiesView'</strong></p>
<pre><code>namespace TiM.Windows.App.View
{
public partial class ProcessIntasnceActivitiesView
{
public static readonly DependencyProperty ContextMenuVisibilityModeProperty =
DependencyProperty.RegisterAttached("ContextMenuVisibilityMode", typeof (string),
typeof (ProcessIntasnceActivitiesView),
new PropertyMetadata("Multiple", OnContextMenuVisibilityModeChanged));
private static void OnContextMenuVisibilityModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var dgrd = d as DataGrid;
if (dgrd != null)
dgrd.ContextMenuOpening += (sender, args) =>
{
switch (e.NewValue.ToString())
{
case "Single":
args.Handled = (sender as DataGrid)?.SelectedItems.Count > 1;
break;
case "Multiple":
args.Handled = !((sender as DataGrid)?.SelectedItems.Count > 1);
break;
}
};
}
...
}
xmlns:local="clr-namespace:TiM.Windows.App.View"
<DataGrid ... local:ProcessIntasnceActivitiesView.ContextMenuVisibilityMode="Single">
</code></pre>
| <p>Handle <code>ContextMenuOpening</code> event of <code>DataGrid</code>.</p>
<pre><code>private void DataGrid_ContextMenuOpening_1(object sender, ContextMenuEventArgs e)
{
e.Handled = (sender as DataGrid).SelectedItems.Count > 1;
}
</code></pre>
<p>You can put this logic into an <code>AttachedProperty</code>.</p>
<pre><code>namespace WpfStackOverflow
{
/// <summary>
/// Interaction logic for Window2.xaml
/// </summary>
public partial class Window2 : Window
{
...
// Using a DependencyProperty as the backing store for ContextMenuVisibilityMode. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ContextMenuVisibilityModeProperty =
DependencyProperty.RegisterAttached("ContextMenuVisibilityMode", typeof(string), typeof(Window2), new PropertyMetadata("Extended", new PropertyChangedCallback(OnContextMenuVisibilityModeChanged)));
private static void OnContextMenuVisibilityModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid dgrd = d as DataGrid;
dgrd.ContextMenuOpening += ((sender, args) => {
if (e.NewValue.ToString() == "Single")
args.Handled = (sender as DataGrid).SelectedItems.Count > 1;
else if (e.NewValue.ToString() == "Extended")
args.Handled = !((sender as DataGrid).SelectedItems.Count > 1);
else {
// do something
}
});
}
...
}
</code></pre>
<p>And apply it to <code>DataGrid</code> : </p>
<pre><code><Window ...
xmlns:local="clr-namespace:WpfStackOverflow"
...>
<DataGrid local:Window2.ContextMenuVisibilityMode="Single" ... />
</code></pre>
|
importing ViewPagerIndicator in android stidio <p>I want to use ViewPagerIndicator in my app. So I need its library. I find these 2 links for downloading, <a href="https://github.com/JakeWharton/ViewPagerIndicator" rel="nofollow">Link1</a> and <a href="http://viewpagerindicator.com/" rel="nofollow">Link2</a>.</p>
<p>But I don't know how can I add it to my project?</p>
<p>this is my build gradle file:</p>
<pre><code> apply plugin: 'com.android.application'
android {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
maven { url "http://dl.bintray.com/populov/maven" }
jcenter()
mavenCentral()
}
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "standup.maxsoft.com.standup"
minSdkVersion 13
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.viewpagerindicator:library:2.4.1@aar'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.google.android.gms:play-services:8.3.0'
compile 'com.viewpagerindicator:library:2.4.1@aar'
compile 'com.google.android.gms:play-services-ads:8.3.0'
compile 'com.google.android.gms:play-services-identity:8.3.0'
compile 'com.google.android.gms:play-services-gcm:8.3.0'
}
</code></pre>
<p>I just copy 2 files in <code>libs.folder</code>. Would you please help me steplly? Thanks</p>
| <p>You can use this dependency (it's an analog):</p>
<pre><code>compile 'fr.avianey.com.viewpagerindicator:library:2.4.1.1@aar'
</code></pre>
|
failed to set up pod network: Unhandled Exception killed plugin <p>I'm trying to play with kubernetes 1.4 install with rkt containers on CoreOS beta (1185.1.0).</p>
<p>In general I have two CoreOS pc machines at home that are configured with etcd2 tls certificates.</p>
<p>I patched the coreos-kubernetes automated generic install script to support etcd2 tls certificates. the latest versions of the worker and controller install scripts are posted at <a href="https://github.com/kfirufk/coreos-kubernetes-multi-node-generic-install-script" rel="nofollow">https://github.com/kfirufk/coreos-kubernetes-multi-node-generic-install-script</a></p>
<p>I used the following environment variables for the controller coreos installation script (ip:<code>10.79.218.2</code>,domain:<code>coreos-2.tux-in.com</code>)</p>
<pre><code>ADVERTISE_IP=10.79.218.2
ETCD_ENDPOINTS="https://coreos-2.tux-in.com:2379,https://coreos-3.tux-in.com:2379"
K8S_VER=v1.4.1_coreos.0
HYPERKUBE_IMAGE_REPO=quay.io/coreos/hyperkube
POD_NETWORK=10.2.0.0/16
SERVICE_IP_RANGE=10.3.0.0/24
K8S_SERVICE_IP=10.3.0.1
DNS_SERVICE_IP=10.3.0.10
USE_CALICO=true
CONTAINER_RUNTIME=rkt
ETCD_CERT_FILE="/etc/ssl/etcd/etcd1.pem"
ETCD_KEY_FILE="/etc/ssl/etcd/etcd1-key.pem"
ETCD_TRUSTED_CA_FILE="/etc/ssl/etcd/ca.pem"
ETCD_CLIENT_CERT_AUTH=true
OVERWRITE_ALL_FILES=true
CONTROLLER_HOSTNAME="coreos-2.tux-in.com"
ETCD_CERT_ROOT_DIR="/etc/ssl/etcd"
ETCD_SCHEME="https"
ETCD_AUTHORITY="coreos-2.tux-in.com:2379"
IS_MASK_UPDATE_ENGINE=false
</code></pre>
<p>and these are the environment variables I used for the worker coreos installation script (ip:<code>10.79.218.3</code>,domain:<code>coreos-3.tux-in.com</code>)</p>
<pre><code>ETCD_AUTHORITY=coreos-3.tux-in.com:2379
ETCD_ENDPOINTS="https://coreos-2.tux-in.com:2379,https://coreos-3.tux-in.com:2379"
CONTROLLER_ENDPOINT=https://coreos-2.tux-in.com
K8S_VER=v1.4.1_coreos.0
HYPERKUBE_IMAGE_REPO=quay.io/coreos/hyperkube
DNS_SERVICE_IP=10.3.0.10
USE_CALICO=true
CONTAINER_RUNTIME=rkt
OVERWRITE_ALL_FILES=true
ADVERTISE_IP=10.79.218.3
ETCD_CERT_FILE="/etc/ssl/etcd/etcd2.pem"
ETCD_KEY_FILE="/etc/ssl/etcd/etcd2-key.pem"
ETCD_TRUSTED_CA_FILE="/etc/ssl/etcd/ca.pem"
ETCD_SCHEME="https"
IS_MASK_UPDATE_ENGINE=false
</code></pre>
<p>after installing kubernetes on both machines, and configuring kubectl properly, when I type <code>kubectl get nodes</code> I get:</p>
<pre><code>NAME STATUS AGE
10.79.218.2 Ready,SchedulingDisabled 1h
10.79.218.3 Ready 1h
</code></pre>
<p><code>kubectl get pods --namespace=kube-system</code> returns</p>
<pre><code>NAME READY STATUS RESTARTS AGE
heapster-v1.2.0-3646253287-j951o 0/2 ContainerCreating 0 1d
kube-apiserver-10.79.218.2 1/1 Running 0 1d
kube-controller-manager-10.79.218.2 1/1 Running 0 1d
kube-dns-v20-u3pd0 0/3 ContainerCreating 0 1d
kube-proxy-10.79.218.2 1/1 Running 0 1d
kube-proxy-10.79.218.3 1/1 Running 0 1d
kube-scheduler-10.79.218.2 1/1 Running 0 1d
kubernetes-dashboard-v1.4.1-ehiez 0/1 ContainerCreating 0 1d
</code></pre>
<p>so <code>heapster-v1.2.0-3646253287-j951o</code>, <code>kube-dns-v20-u3pd0</code> and <code>kubernetes-dashboard-v1.4.1-ehiez</code> are stuck in ContainerCreating status.</p>
<p>when I run <code>kubectl describe</code> on any of them, I basically get the same error: <code>Error syncing pod, skipping: failed to SyncPod: failed to set up pod network: Unhandled Exception killed plugin</code>.</p>
<p>for example, <code>kubectl describe pods kubernetes-dashboard-v1.4.1-ehiez --namespace kube-system</code> returns: </p>
<pre><code>Name: kubernetes-dashboard-v1.4.1-ehiez
Namespace: kube-system
Node: 10.79.218.3/10.79.218.3
Start Time: Mon, 17 Oct 2016 23:31:43 +0300
Labels: k8s-app=kubernetes-dashboard
kubernetes.io/cluster-service=true
version=v1.4.1
Status: Pending
IP:
Controllers: ReplicationController/kubernetes-dashboard-v1.4.1
Containers:
kubernetes-dashboard:
Container ID:
Image: gcr.io/google_containers/kubernetes-dashboard-amd64:v1.4.1
Image ID:
Port: 9090/TCP
Limits:
cpu: 100m
memory: 50Mi
Requests:
cpu: 100m
memory: 50Mi
State: Waiting
Reason: ContainerCreating
Ready: False
Restart Count: 0
Liveness: http-get http://:9090/ delay=30s timeout=30s period=10s #success=1 #failure=3
Volume Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-svbiv (ro)
Environment Variables: <none>
Conditions:
Type Status
Initialized True
Ready False
PodScheduled True
Volumes:
default-token-svbiv:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-svbiv
QoS Class: Guaranteed
Tolerations: CriticalAddonsOnly=:Exists
Events:
FirstSeen LastSeen Count From SubobjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
1d 25s 9350 {kubelet 10.79.218.3} Warning FailedSync Error syncing pod, skipping: failed to SyncPod: failed to set up pod network: Unhandled Exception killed plugin
</code></pre>
<p>I'm guessing that pod networking isn't working because of faulty calico configuration..</p>
<p>so I tried to install calicoctl rkt container, but had problems with that. but that's a different stackoverflow question :) <a href="http://stackoverflow.com/questions/39861422/starting-calicoctl-container-on-coreos">starting calicoctl container on coreos</a></p>
<p>so I can't really check if calico works properly. </p>
<p>this is the calico-network systemd service file for the controller node:</p>
<pre><code>[Unit]
Description=Calico per-host agent
Requires=network-online.target
After=network-online.target
[Service]
Slice=machine.slice
Environment=CALICO_DISABLE_FILE_LOGGING=true
Environment=HOSTNAME=10.79.218.3
Environment=IP=10.79.218.3
Environment=FELIX_FELIXHOSTNAME=10.79.218.3
Environment=CALICO_NETWORKING=true
Environment=NO_DEFAULT_POOLS=true
Environment=ETCD_ENDPOINTS=https://coreos-2.tux-in.com:2379,https://coreos-3.tux-in.com:2379
Environment=ETCD_AUTHORITY=coreos-3.tux-in.com:2379
Environment=ETCD_SCHEME=https
Environment=ETCD_CA_CERT_FILE=/etc/ssl/etcd/ca.pem
Environment=ETCD_CERT_FILE=/etc/ssl/etcd/etcd2.pem
Environment=ETCD_KEY_FILE=/etc/ssl/etcd/etcd2-key.pem
ExecStart=/usr/bin/rkt run --inherit-env --stage1-from-dir=stage1-fly.aci --volume=var-run-calico,kind=host,source=/var/run/calico --volume=modules,kind=host,source=/lib/modules,readOnly=false --mount=volume=modules,target=/lib/modules --volume=dns,kind=host,source=/etc/resolv.conf,readOnly=true --volume=etcd-tls-certs,kind=host,source=/etc/ssl/etcd,readOnly=true --mount=volume=dns,target=/etc/resolv.conf --mount=volume=etcd-tls-certs,target=/etc/ssl/etcd --mount=volume=var-run-calico,target=/var/run/calico --trust-keys-from-https quay.io/calico/node:v0.22.0
KillMode=mixed
Restart=always
TimeoutStartSec=0
[Install]
WantedBy=multi-user.target
</code></pre>
<p>and is the calico-node service file for the worker node:</p>
<pre><code>[Unit]
Description=Calico per-host agent
Requires=network-online.target
After=network-online.target
[Service]
Slice=machine.slice
Environment=CALICO_DISABLE_FILE_LOGGING=true
Environment=HOSTNAME=10.79.218.2
Environment=IP=10.79.218.2
Environment=FELIX_FELIXHOSTNAME=10.79.218.2
Environment=CALICO_NETWORKING=true
Environment=NO_DEFAULT_POOLS=false
Environment=ETCD_ENDPOINTS=https://coreos-2.tux-in.com:2379,https://coreos-3.tux-in.com:2379
ExecStart=/usr/bin/rkt run --inherit-env --stage1-from-dir=stage1-fly.aci --volume=var-run-calico,kind=host,source=/var/run/calico --volume=modules,kind=host,source=/lib/modules,readOnly=false --mount=volume=modules,target=/lib/modules --volume=dns,kind=host,source=/etc/resolv.conf,readOnly=true --volume=etcd-tls-certs,kind=host,source=/etc/ssl/etcd,readOnly=true --mount=volume=dns,target=/etc/resolv.conf --mount=volume=etcd-tls-certs,target=/etc/ssl/etcd --mount=volume=var-run-calico,target=/var/run/calico --trust-keys-from-https quay.io/calico/node:v0.22.0
KillMode=mixed
Environment=ETCD_CA_CERT_FILE=/etc/ssl/etcd/ca.pem
Environment=ETCD_CERT_FILE=/etc/ssl/etcd/etcd1.pem
Environment=ETCD_KEY_FILE=/etc/ssl/etcd/etcd1-key.pem
Restart=always
TimeoutStartSec=0
[Install]
WantedBy=multi-user.target
</code></pre>
<p>and this is the content of <code>/etc/kubernetes/cni/net.d/10-calico.conf</code> of the controller node:</p>
<pre><code>{
"name": "calico",
"type": "flannel",
"delegate": {
"type": "calico",
"etcd_endpoints": "https://coreos-2.tux-in.com:2379,https://coreos-3.tux-in.com:2379",
"etcd_key_file": "/etc/ssl/etcd/etcd1-key.pem",
"etcd_cert_file": "/etc/ssl/etcd/etcd1.pem",
"etcd_ca_cert_file": "/etc/ssl/etcd/ca.pem",
"log_level": "none",
"log_level_stderr": "info",
"hostname": "10.79.218.2",
"policy": {
"type": "k8s",
"k8s_api_root": "http://127.0.0.1:8080/api/v1/"
}
}
}
</code></pre>
<p>and this is the <code>/etc/kubernetes/cni/net.d/10-calico.conf</code> of the worker node:</p>
<pre><code>{
"name": "calico",
"type": "flannel",
"delegate": {
"type": "calico",
"etcd_endpoints": "https://coreos-2.tux-in.com:2379,https://coreos-3.tux-in.com:2379",
"etcd_key_file": "/etc/ssl/etcd/etcd2-key.pem",
"etcd_cert_file": "/etc/ssl/etcd/etcd2.pem",
"etcd_ca_cert_file": "/etc/ssl/etcd/ca.pem",
"log_level": "debug",
"log_level_stderr": "info",
"hostname": "10.79.218.3",
"policy": {
"type": "k8s",
"k8s_api_root": "https://coreos-2.tux-in.com:443/api/v1/",
"k8s_client_key": "/etc/kubernetes/ssl/worker-key.pem",
"k8s_client_certificate": "/etc/kubernetes/ssl/worker.pem"
}
}
}
</code></pre>
<p>now idea how to investigate the issue further.
I understand that since new calico-cni was moved to go, it doesn't store log information in a log file anymore, so i'm lost from here.
any information regarding the issue would be greatly appreciated.</p>
<p>thanks!</p>
| <p>The "Unhandled Exception Killed plugin" error message is being generated by the Calico CNI plugin. From my experience that means it is unlikely to be something wrong with the <code>calico-node.service</code> causing that error.</p>
<p>As such it is <em>probably</em> something subtly wrong with you CNI network configuration. Could you share that file?</p>
<p>The CNI plugin should also emit more detailed logging information - either to <code>stderr</code> or to <code>/var/log/calico/cni/calico.log</code> based on how its configured in your CNI network config. I suspect that file will give you more clues into exactly what is going wrong.</p>
|
Python While Loop <p>Write function lastfirst() that takes one argument a list of strings of the format â and returns a list consisting two lists: </p>
<p>(a) A list of all the ï¬rst names </p>
<p>(b) A list of all the last names </p>
<pre><code>>>> lastfirst(['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'])
[['Len', 'Kate','Bob'], ['Gerber', 'Fox', 'Dunn']
</code></pre>
<p>I figured out how to solve this problem using for loop but I can't figure out how to solve it using the while loop.</p>
| <p>With the while loop you need a counter or iterator since the for loop is not creating the iterator for you.</p>
<pre><code># http://stackoverflow.com/questions/39934280/python-while-loop
# uses an iterator effectively making it a for loop
def lastFirst_iterator(nameList):
nameListIter = iter(nameList)
firstNames = []
lastNames = []
try:
while True:
last, first = next(nameListIter).split(', ')
firstNames.append(first)
lastNames.append(last)
except StopIteration:
return [firstNames, lastNames]
# uses a counter a more c like implimentation
def lastFirst_counter(nameList):
firstNames = []
lastNames = []
i = 0
while i<len(nameList):
last, first = nameList[i].split(', ')
firstNames.append(first)
lastNames.append(last)
i += 1
return [firstNames, lastNames]
# way you should do it
def lastFirst_should(nameList):
seperatedNames = tuple(lastFirst.split(', ') for lastFirst in nameList)
return [[lastFirst[d] for lastFirst in seperatedNames] for d in range(-1, 1)]
nameList = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
print(lastFirst_iterator(nameList))
print(lastFirst_counter(nameList))
print(lastFirst_should(nameList))
</code></pre>
|
Ways to do inter-frame video compression in AVFoundation <p>I've created a process to generate video "slideshows" from collections of photographs and images in an application that I'm building. The process is functioning correctly, but creates unnecessarily large files given that any photographs included in the video repeat for 100 to 150 frames unchanged. I've included whatever compression I can find in AVFoundation, which mostly applies intra-frame techniques and tried to find more information on inter-frame compression in AVFoundation. Unfortunately, there are only a few references that I've been able to find and nothing that has let me get it to work.</p>
<p>I'm hoping that someone can steer me in the right direction. The code for the video generator is included below. I've not included the code for fetching and preparing the individual frames (called below as self.getFrame()) since that seems to be working fine and gets quite complex since it handles photos, videos, adding title frames, and doing fade transitions. For repeated frames, it returns a structure with the frame image and a counter for the number of output frames to include.</p>
<pre><code> // Create a new AVAssetWriter Instance that will build the video
assetWriter = createAssetWriter(path: filePathNew, size: videoSize!)
guard assetWriter != nil else
{
print("Error converting images to video: AVAssetWriter not created.")
inProcess = false
return
}
let writerInput = assetWriter!.inputs.filter{ $0.mediaType == AVMediaTypeVideo }.first!
let sourceBufferAttributes : [String : AnyObject] = [
kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_32ARGB) as AnyObject,
kCVPixelBufferWidthKey as String : videoSize!.width as AnyObject,
kCVPixelBufferHeightKey as String : videoSize!.height as AnyObject,
AVVideoMaxKeyFrameIntervalKey as String : 50 as AnyObject,
AVVideoCompressionPropertiesKey as String : [
AVVideoAverageBitRateKey: 725000,
AVVideoProfileLevelKey: AVVideoProfileLevelH264Baseline30,
] as AnyObject
]
let pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput, sourcePixelBufferAttributes: sourceBufferAttributes)
// Start the writing session
assetWriter!.startWriting()
assetWriter!.startSession(atSourceTime: kCMTimeZero)
if (pixelBufferAdaptor.pixelBufferPool == nil) {
print("Error converting images to video: pixelBufferPool nil after starting session")
inProcess = false
return
}
// -- Create queue for <requestMediaDataWhenReadyOnQueue>
let mediaQueue = DispatchQueue(label: "mediaInputQueue")
// Initialize run time values
var presentationTime = kCMTimeZero
var done = false
var nextFrame: FramePack? // The FramePack struct has the frame to output, noDisplays - the number of times that it will be output
// and an isLast flag that is true when it's the final frame
writerInput.requestMediaDataWhenReady(on: mediaQueue, using: { () -> Void in // Keeps invoking the block to get input until call markAsFinished
nextFrame = self.getFrame() // Get the next frame to be added to the output with its associated values
let imageCGOut = nextFrame!.frame // The frame to output
if nextFrame!.isLast { done = true } // Identifies the last frame so can drop through to markAsFinished() below
var frames = 0 // Counts how often we've output this frame
var waitCount = 0 // Used to avoid an infinite loop if there's trouble with writer.Input
while (frames < nextFrame!.noDisplays) && (waitCount < 1000000) // Need to wait for writerInput to be ready - count deals with potential hung writer
{
waitCount += 1
if waitCount == 1000000 // Have seen it go into 100s of thousands and succeed
{
print("Exceeded waitCount limit while attempting to output slideshow frame.")
self.inProcess = false
return
}
if (writerInput.isReadyForMoreMediaData)
{
waitCount = 0
frames += 1
autoreleasepool
{
if let pixelBufferPool = pixelBufferAdaptor.pixelBufferPool
{
let pixelBufferPointer = UnsafeMutablePointer<CVPixelBuffer?>.allocate(capacity: 1)
let status: CVReturn = CVPixelBufferPoolCreatePixelBuffer(
kCFAllocatorDefault,
pixelBufferPool,
pixelBufferPointer
)
if let pixelBuffer = pixelBufferPointer.pointee, status == 0
{
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer)
let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
// Set up a context for rendering using the PixelBuffer allocated above as the target
let context = CGContext(
data: pixelData,
width: Int(self.videoWidth),
height: Int(self.videoHeight),
bitsPerComponent: 8,
bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer),
space: rgbColorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue
)
// Draw the image into the PixelBuffer used for the context
context?.draw(imageCGOut, in: CGRect(x: 0.0,y: 0.0,width: 1280, height: 720))
// Append the image (frame) from the context pixelBuffer onto the video file
_ = pixelBufferAdaptor.append(pixelBuffer, withPresentationTime: presentationTime)
presentationTime = presentationTime + CMTimeMake(1, videoFPS)
// We're done with the PixelBuffer, so unlock it
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
}
pixelBufferPointer.deinitialize()
pixelBufferPointer.deallocate(capacity: 1)
} else {
NSLog("Error: Failed to allocate pixel buffer from pool")
}
}
}
}
</code></pre>
<p>Thanks in advance for any suggestions.</p>
| <p>It looks like you're </p>
<ol>
<li>appending a bunch of redundant frames to your video, </li>
<li>labouring under a misapprehension: that video files must have a constant framerate that is high, e.g. 30fps.</li>
</ol>
<p>If, for example, you're showing a slideshow of 3 images over a duration of 15 seconds, then you <em>need only output 3 images</em>, with presentation timestamps of 0s, 5s, 10s and an <code>assetWriter.endSession(atSourceTime:</code>) of 15s, not 15s * 30 FPS = 450 frames . </p>
<p>In other words, your frame rate is <em>way too high</em> - for the best interframe compression money can buy, lower your frame rate to the bare minimum number of frames you need and all will be well<sup>*</sup>.</p>
<p><sup>*<sub>I've seen some video services/players choke on unusually low framerates,<br>
so you may need a minimum framerate and <em>some</em> redundant frames, e.g. 1frame/5s, ymmv</sub></sup></p>
|
Navigation between page <p>I'm writing a small WPF app with only 3 pages (for now). I'm using DataTemplate and ContentControl in the main window to display and switch between my pages. (See code sample below). It's working but I have a few concerns:</p>
<ol>
<li><p>The DataTemplate use parameterless constructor only. If I add one then It can't find the constructor. </p></li>
<li><p>The 'registration' is done in the xaml and I cannot use Dependency Injection to link Views with ViewModels.</p></li>
</ol>
<p><strong>Questions:</strong></p>
<p>Is there a way to change that without using third party tool? </p>
<p>If the only good option is to use a tool, which ones should I consider?</p>
<pre><code><Window.Resources>
<DataTemplate DataType="{x:Type pageViewModels:HomePageViewModel}">
<pageViews:HomePageView />
</DataTemplate>
<DataTemplate DataType="{x:Type pageViewModels:GamePageViewModel}">
<pageViews:GamePageView />
</DataTemplate>
</Window.Resources>
<DockPanel>
<Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
<ItemsControl ItemsSource="{Binding PageViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"
Margin="2,5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</code></pre>
<p><strong>Edit</strong>
To clarify, I want to inject a class in the constructor of my viewsModels, but if I do that then the navigation within my application is broken because the dataTemplate is looking for the parameterless constructor.</p>
| <p>It looks like my problem has been very well explained in this <a href="http://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates">post</a>.</p>
<p>In short, I need to implement a ViewModelLocator pattern in order to fix all my concerns.</p>
|
gawk and grep using same pattern but need different treatement for escape sequence <p>I have a bash shell script (named <code>testawk</code> to replace a line containing a pattern (1st arg) with one or more than one line (2nd arg) and operates on the filename given in 3rd arg. The shell script is given below: </p>
<pre><code>#!/bin/bash
if grep -s "$1" "$3" > /dev/null; then
gawk -v nm2="$2" -v nm1="$1" '{ if ($0 ~ nm1) print nm2;else print $0}' "$3" > "$3".bak
mv "$3".bak "$3"
fi
</code></pre>
<p>If I have a file named "aa" containing the following:</p>
<pre><code>a;
b<*c;
</code></pre>
<p>And, if I run <code>testawk</code> as:</p>
<pre><code>./testawk "a;" "x<*y;" "aa"
</code></pre>
<p>aa contains:</p>
<pre><code>x<*y;
b<*c;
</code></pre>
<p>But, if I run <code>testawk</code> on original <code>aa</code> file again as:</p>
<pre><code>./testawk "b<*c;" "x<*y;" "aa"
</code></pre>
<p><code>aa</code> contains now as (unchanged content):</p>
<pre><code>a;
b<*c;
</code></pre>
<p>Because, <code>grep "b<*c;" "aa"</code> cannot find the pattern.
To make <code>grep</code> happy, if I use escape sequences as:</p>
<pre><code>grep "b<\*c;" "aa"
</code></pre>
<p>It could match and shows:</p>
<pre><code>b<*c;
</code></pre>
<p>if I use testawk using the escape sequence as below:</p>
<pre><code>./testawk "b<\*c;" "x<*y;" "aa"
</code></pre>
<p><code>gawk</code> does not like that and complains as:</p>
<pre><code>gawk: warning: escape sequence `\*' treated as plain `*'
</code></pre>
<p>And <code>aa</code> gets no changed content as:</p>
<pre><code>a;
b<*c;
</code></pre>
<p>Any remedy to make both <code>grep</code> and <code>gawk</code> happy to find and replace <code>b<*c;</code>
Please suggest how to replace <code>b<*c;</code>.</p>
| <p>This should do what I think you are asking for:</p>
<pre><code>if awk -v nm2="$2" -v nm1="$1" 'index($0,nm1){f=1; $0=nm2} 1; END{exit !f}' "$3" > "${3}.bak"
then
mv "${3}.bak" "$3"
# do stuff with modified file "$3"
else
rm -f "${3}.bak"
# do stuff with unmodified file "$3"
fi
</code></pre>
<p>No need to escape anything except backslashes and we can deal with that differently if you have those.</p>
|
Calculation in 1 line VBS <p>How can I make this Calculator work if the user enters 1+1?
It only works if I enter 1 + 1 ;C
The calculation must be in 1 line.</p>
<pre><code>x = inputbox("Calculation", "Calculator", "1+1")
y = Split(x)
if not isnumeric (y(0)) then
wscript.quit
end if
if not isnumeric (y(2)) then
wscript.quit
end if
if y(1) = "+" then
z = int(y(0)) + int(y(2))
msgbox(z)
end if
if y(1) = "-" then
z = int(y(0)) - int(y(2))
msgbox(z)
end if
if y(1) = "*" then
z = int(y(0)) * int(y(2))
msgbox(z)
end if
if y(1) = "/" then
z = int(y(0)) / int(y(2))
msgbox(z)
end if
if y(1) = "%" then
z = int(y(0)) MOD int(y(2))
msgbox(z)
end if
</code></pre>
<p>Thanks for any Answer!</p>
| <p>Try next code snippet (commented for explanation):</p>
<pre><code>Dim ii, sOperator, strExpr, y
strExpr = inputbox("Calculation", "Calculator", "1+1")
' insert spaces around all operators
For Each sOperator in Array("+","-","*","/","%")
strExpr = Trim( Replace( strExpr, sOperator, Space(1) & sOperator & Space(1)))
Next
' replace all multi spaces with a single space
Do While Instr( strExpr, Space(2))
strExpr = Trim( Replace( strExpr, Space(2), Space(1)))
Loop
y = Split(strExpr)
''' your script continues here
</code></pre>
<p><strong>Another approach</strong> (allows more than pure <em>arithmetic</em> operations) using <a href="https://msdn.microsoft.com/en-us/library/0z5x4094(v=vs.84).aspx" rel="nofollow"><code>Eval</code> Function</a> (which <em>evaluates an expression and returns the result</em>) and basic <a href="https://msdn.microsoft.com/en-us/library/53f3k80h(v=vs.84).aspx" rel="nofollow">error handling</a>:</p>
<pre><code>option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim strExpr, strInExp, strLastY, yyy
strInExp = "1+1"
strLastY = ""
Do While True
strExpr = inputbox("Last calculation:" & vbCR & strLastY, "Calculator", strInExp)
If Len( strExpr) = 0 Then Exit Do
''' in my locale, decimal separator is a comma but VBScript arithmetics premises a dot
strExpr = Replace( strExpr, ",", ".") ''' locale specific
On Error Resume Next ' enable error handling
yyy = Eval( strExpr)
If Err.Number = 0 Then
strInExp = CStr( yyy)
strLastY = strExpr & vbTab & strInExp
strResult = strResult & vbNewLine & strLastY
Else
strLastY = strExpr & vbTab & "!!! 0x" & Hex(Err.Number) & " " & Err.Description
strInExp = strExpr
strResult = strResult & vbNewLine & strLastY
End If
On Error GoTo 0 ' disable error handling
Loop
Wscript.Echo strResult
Wscript.Quit
</code></pre>
<p><strong>Sample output</strong>:</p>
<pre><code>==> cscript //NOLOGO D:\VB_scripts\SO\39934370.vbs
39934370.vbs
1+1 2
2/4 0,5
0.5**8 !!! 0x3EA Syntax error
0.5*8 4
4=4 True
True+5 4
4=5 False
False+5 5
5 5
==>
</code></pre>
|
NoClassDefFoundError. Why??? How can I fix it? <p>I wrote my classloader:</p>
<pre><code>package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class PluginManager extends ClassLoader {
private final String pluginRootDirectory;
public PluginManager(String pluginRootDirectory) {
this.pluginRootDirectory = pluginRootDirectory;
}
public Plugin load(String pluginName, String pluginClassName) {
String name = pluginName + "." + pluginClassName;
try {
Class clazz;
try {
clazz = super.findSystemClass(name);
} catch (ClassNotFoundException e) {
String fileName = pluginRootDirectory + "\\" + pluginName + "\\" + pluginClassName + ".class";
try (FileInputStream fin = new FileInputStream(fileName)) {
byte[] buffer = new byte[(int) (new File(fileName).length())];
fin.read(buffer);
clazz = defineClass(name, buffer, 0, buffer.length);
}
}
return (Plugin)clazz.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException ignored) {
return null;
}
}
</code></pre>
<p>}</p>
<p>When I run it:</p>
<pre><code>package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
public class PluginManagerTest {
public static void main(String[] args) {
String pluginRootDirectory = "D:\\sbt\\target\\classes\\ru\\sberbank\\school\\homework8";
PluginManager pluginManager = new PluginManager(pluginRootDirectory);
Plugin plugin = pluginManager.load("plugin", "PluginImpl");
if (plugin != null) {
plugin.doUseful();
}
}
}
</code></pre>
<blockquote>
<p>Exception in thread "main" java.lang.NoClassDefFoundError:
plugin/PluginImpl (wrong name:
ru/sberbank/school/homework8/plugin/PluginImpl) at
java.lang.ClassLoader.defineClass1(Native Method)</p>
</blockquote>
<p><strong>I get NoClassDefFoundError. Why??? How can I fix it???</strong></p>
<p>Help me, please! </p>
<pre><code>package ru.sberbank.school.homework8.plugin;
public class PluginImpl implements Plugin {
@Override
public void doUseful() {
System.out.println("My plugin!");
}
}
</code></pre>
| <p>You get this error because you don't provide the correct FQN of your class, indeed in your <code>load</code> method, you try to find the class corresponding to <code>pluginName + "." + pluginClassName</code> that will be in your case <code>plugin.PluginImpl</code> but the package name of your class <code>PluginImpl</code> is actually <code>ru.sberbank.school.homework8.plugin</code> such that the real FQN of your class is <code>ru.sberbank.school.homework8.plugin.PluginImpl</code>.</p>
<p>To fix this problem, you need to replace:</p>
<pre><code>Plugin plugin = pluginManager.load("plugin", "PluginImpl");
</code></pre>
<p>With:</p>
<pre><code>Plugin plugin = pluginManager.load("ru.sberbank.school.homework8.plugin", "PluginImpl");
</code></pre>
<p>Or you could modify your method <code>load</code> to add a prefix assuming that you will always retrieve your plugins from the same root package:</p>
<pre><code>public Plugin load(String pluginName, String pluginClassName) {
String name = "ru.sberbank.school.homework8." + pluginName + "." + pluginClassName;
</code></pre>
|
Spring Boot Response Entity doesn't return JSON <p>When i return my POJO from RestController it's transforms in JSON object.
But when i try to return <code>new ResponseEntity<>("success", HttpStatus.CREATED);</code>
controller returns plain-text. What's wrong?</p>
<p>My RestController:</p>
<pre><code> @RequestMapping(value = "/register", method = RequestMethod.POST,consumes = "application/json", produces="application/json")
public ResponseEntity<?> registerUser(@RequestBody User user) throws MessagingException {
if(registrationService.canRegister(user.getEmail())){
registrationService.registerUser(user);
logger.info("Registered user "+user.getEmail());
return new ResponseEntity<>("success", HttpStatus.CREATED);
}
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
</code></pre>
<p>My dependencies:</p>
<pre><code> <dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</code></pre>
<p>Spring Boot version 1.4.1</p>
| <p><code>"success"</code> as a String cannot be cast to JSON format. Hence, spring controller returns plain/text.Generally, for any object to be cast as JSON, it must be in the format of a key value pair, so all POJOs can be converted to corresponding key-value pairs where <code>key</code> is the property name and <code>value</code> is property's value. You can have a look at this page to validate what constitutes a valid json.
<a href="https://jsonformatter.curiousconcept.com/" rel="nofollow">https://jsonformatter.curiousconcept.com/</a></p>
|
Inequality in Mysql with count() <p>I have the following structure : </p>
<pre><code>Table Author :
idAuthor,
Name
+----------+-------+
| idAuthor | Name |
+----------+-------+
| 1 | Renee |
| 2 | John |
| 3 | Bob |
| 4 | Bryan |
+----------+-------+
Table Publication:
idPublication,
Title,
Type,
Date,
Journal,
Conference
+---------------+--------------+------+-------------+------------+-----------+
| idPublication | Title | Date | Type | Conference | Journal |
+---------------+--------------+------+-------------+------------+-----------+
| 1 | Flower thing | 2008 | book | NULL | NULL |
| 2 | Bees | 2009 | article | NULL | Le Monde |
| 3 | Wasps | 2010 | inproceding | KDD | NULL |
| 4 | Whales | 2010 | inproceding | DPC | NULL |
| 5 | Lyon | 2011 | article | NULL | Le Figaro |
| 6 | Plants | 2012 | book | NULL | NULL |
| 7 | Walls | 2009 | proceeding | KDD | NULL |
| 8 | Juices | 2010 | proceeding | KDD | NULL |
| 9 | Fruits | 2010 | proceeding | DPC | NULL |
| 10 | Computers | 2010 | inproceding | DPC | NULL |
| 11 | Phones | 2010 | inproceding | DPC | NULL |
| 12 | Creams | 2010 | proceeding | DPC | NULL |
| 13 | Love | 2010 | proceeding | DPC | NULL |
+---------------+--------------+------+-------------+------------+-----------+
Table author_has_publication :
Author_idAuthor,
Publication_idPublication
+-----------------+---------------------------+
| Author_idAuthor | Publication_idPublication |
+-----------------+---------------------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 1 | 5 |
| 2 | 5 |
| 3 | 5 |
| 3 | 6 |
| 4 | 7 |
| 4 | 8 |
| 4 | 9 |
| 4 | 10 |
| 3 | 11 |
| 3 | 12 |
| 2 | 13 |
+-----------------+---------------------------+
</code></pre>
<p>I want to obtain the list of all authors having published at least 2 times at conference DPC in 2010.
I achieved to get the list of autors that have published something, and the number of publication for each, but I can't get my 'at least 2' factor. </p>
<p>My following query </p>
<pre><code>SELECT author.name, COUNT(name) FROM author INNER JOIN author_has_publication ON author.idAuthor=author_has_publication.Author_idAuthor INNER JOIN publication ON author_has_publication.Publication_idPublication=publication.idPublication AND publication.date=2010 AND publication.conference='DPC'GROUP BY author.name;
</code></pre>
<p>returns the following result (which is good) </p>
<pre><code>+-------+-------------+
| name | COUNT(name) |
+-------+-------------+
| Bob | 2 |
| Bryan | 3 |
| John | 1 |
+-------+-------------+
</code></pre>
<p>but when I try to select only the one with a count(name)>=2, i got an error.
I tried this query : </p>
<pre><code>SELECT author.name, COUNT(name) FROM author INNER JOIN author_has_publication ON author.idAuthor=author_has_publication.Author_idAuthor INNER JOIN publication ON author_has_publication.Publication_idPublication=publication.idPublication AND publication.date=2010 AND publication.conference='DPC'GROUP BY author.name WHERE COUNT(name)>=2;
</code></pre>
| <p>When you use aggregation funcion you can filter with a proper operator named HAVING </p>
<p>Having worok on the result of the query (then pn the aggrgated result like count() ) instead of where that work on the original value of the tables rows</p>
<pre><code>SELECT author.name, COUNT(name)
FROM author INNER JOIN author_has_publication
ON author.idAuthor=author_has_publication.Author_idAuthor
INNER JOIN publication
ON author_has_publication.Publication_idPublication=publication.idPublication
AND publication.date=2010 AND publication.conference='DPC'
GROUP BY author.name
HAVING COUNT(name)>=2;
</code></pre>
|
Using if statement to deal cards <p>I am trying to deal an x amount of cards to a player depending on how many they already have in their hand (max of 5). But to insure that you don't get dealt the same card twice, or dealt a card that has already been played I've used an if Statement.</p>
<pre><code>Card[] hand = new Card[5];
public void dealCard() {
int cardCount = 0;
Random ran = new Random();
if (cardCount < 5) {
int times = 5 - cardCount;
for (int l = 0; l < times; l++) {
int index = ran.nextInt(deck.length);
if (deck[index] != null) {
hand[cardCount] = deck[index];
deck[index] = null;
cardCount++;
}
}
}
}
</code></pre>
<p>It seemed to work at first but every so often the last card, and its always the last card, is null. I was told that it would probably be better to use a while loop instead, but just for the purpose of learning what have I done wrong here.</p>
| <p>Your <code>for</code> loop is always executed exactly five times, no matter how often you encounter a <code>null</code> within the loop's body. You can verify this by manipulating the size of <code>deck</code> to something <code>< 5</code>. If your method were working correct, it should get caught in an endless loop. instead, you will get at least <code>5 - deck.size</code> many <code>null</code>s. A quick& dirty fix would be to decremt <code>l</code> in case you encounter a <code>null</code>:</p>
<pre><code>if (deck[index] != null) {
// ...
} else /* if (deck[index] == null) */ {
--l;
}
</code></pre>
<p>I would recommend a different strategy alltogether. Instead of generating a random index every time you want to draw a card, you could determin the order of all cards up-front, e.g. with the <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle" rel="nofollow">Fisher-Yates-Shuffle</a>. This way, you need only to remember how many cards were drawn and extract the next card from your array/list/queue.</p>
|
read file line by line including multiple newline characters <p>I am trying to read a file of unknown size line by line including single or multiple newline characters.
for example if my sample.txt file looks like this</p>
<pre><code>abc cd er dj
text
more text
zxc cnvx
</code></pre>
<p>I want my strings to look something like this</p>
<pre><code>string1 = "abc cd er dj\n";
string2 = "text\n\n";
string3 = "more text\n\n\n";
string4 = "zxc convex";
</code></pre>
<p>I can't seem to come up with solution that works properly. I have tried following code to get the length of each line including newline characters but it gives me incorrect length</p>
<pre><code>while((temp = fgetc(input)) != EOF) {
if (temp != '\n') {
length++;
}
else {
if (temp == '\n') {
while ((temp = fgetc(input)) == '\n') {
length++;
}
}
length = 0;
}
}
</code></pre>
<p>I was thinking, if I can get length of each line including newline character(s) and then I can malloc string of that length and then read that size of string using fread but I am not sure if that would work because I will have to move the file pointer to get the next string. </p>
<p>I also don't want to use buffer because I don't know the length of each line. Any sort of help will be appreciated.</p>
| <p>If the lines are just short and there aren't many of them, you could use <code>realloc</code> to reallocate memory as needed. Or you can use smaller (or larger) chunks and reallocate. It's a little more wasteful but hopefully it should average out in the end.</p>
<p>If you want to use just one allocation, then find the start of the next non-empty line and save the file position (use <code>ftell</code>). Then get the difference between the current position and the previous start position and you know how much memory to allocate. For the reading yes you have to seek back and forth but if it's not to big all data will be in the buffer to it's just modifying some pointers. After reading then seek to the saved position and make it the next start position.</p>
<p>Then you could of course the possibility to <a href="https://en.wikipedia.org/wiki/Memory-mapped_file" rel="nofollow">memory-map the file</a>. This will put the file contents into your memory map like it was all allocated. For a 64-bit system the address space is big enough so you should be able to map multi-gigabyte files. Then you don't need to seek or allocate memory, all you do is manipulate pointers instead of seeking. Reading is just a simply memory copying (but then since the file is "in" memory already you don't really need it, just save the pointers instead).</p>
<hr>
<p>For a <em>very</em> simple example on <a href="http://en.cppreference.com/w/c/io/fseek" rel="nofollow"><code>fseek</code></a> and <a href="http://en.cppreference.com/w/c/io/ftell" rel="nofollow"><code>ftell</code></a>, that is somewhat related to your problem, I put together this little program for you. It doesn't really do anything special but it shows how to use the functions in a way that could be used for a prototype of the second method I discussed above.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *file = fopen("some_text_file.txt", "r");
// The position after a successful open call is always zero
long start_of_line = 0;
int ch;
// Read characters until we reach the end of the file or there is an error
while ((ch = fgetc(file)) != EOF)
{
// Hit the *first* newline (which differs from your problem)
if (ch == '\n')
{
// Found the first newline, get the current position
// Note that the current position is the position *after* the newly read newline
long current_position = ftell(file);
// Allocate enough memory for the whole line, including newline
size_t bytes_in_line = current_position - start_of_line;
char *current_line = malloc(bytes_in_line + 1); // +1 for the string terminator
// Now seek back to the start of the line
fseek(file, start_of_line, SEEK_SET); // SEEK_SET means the offset is from the beginning of the file
// And read the line into the buffer we just allocated
fread(current_line, 1, bytes_in_line, file);
// Terminate the string
current_line[bytes_in_line] = '\0';
// At this point, if everything went well, the file position is
// back at current_position, because the fread call advanced the position
// This position is the start of the next line, so we use it
start_of_line = current_position;
// Then do something with the line...
printf("Read a line: %s", current_line);
// Finally free the memory we allocated
free(current_line);
}
// Continue loop reading character, to read the next line
}
// Did we hit end of the file, or an error?
if (feof(file))
{
// End of the file it is
// Now here's the tricky bit. Because files doesn't have to terminated
// with a newline, at this point we could actually have some data we
// haven't read. That means we have to do the whole thing above with
// the allocation, seeking and reading *again*
// This is a good reason to extract that code into its own function so
// you don't have to repeat it
// I will not repeat the code my self. Creating a function containing it
// and calling it is left as an exercise
}
fclose(file);
return 0;
}
</code></pre>
<p>Please note that for brevity's sake the program doesn't contain any error handling. It should also be noted that I haven't actually <em>tried</em> the program, not even tried to compile it. It's all written ad hoc for this answer.</p>
|
How to handle special characters like : and , in .htaccess rules? <p>How i can get <strong>a</strong> and <strong>b</strong> values from urls like this:<br></p>
<pre><code>http://127.0.0.1:8080/a:4522,b:846
</code></pre>
<p>I add this code to .htaccess for redirect all links to index.php but not working when use <code>:</code> and <code>,</code> character<br></p>
<pre><code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
</code></pre>
| <p>For <code>http://127.0.0.1:8080/a:4522,b:846</code> the request URI equals to <code>/a:4522,b:846</code>. And the <code>.htaccess</code> directives put the request URI into <code>path</code> GET parameter. So you can simply parse <code>$_GET['path']</code> in PHP:</p>
<pre><code><?php
$vars = [];
if ($path = isset($_GET['path']) ? $_GET['path'] : null) {
foreach (explode(',', $path) as $part) {
$tmp = explode(':', $part);
if (count($tmp) == 2) {
$vars[$tmp[0]] = $tmp[1];
}
}
}
var_dump($vars);
</code></pre>
<p><em>Output</em></p>
<pre><code>array(2) {
["a"]=>
string(4) "4522"
["b"]=>
string(3) "846"
}
</code></pre>
<h2>Sample configuration</h2>
<p><strong>/etc/apache2/vhosts.d/01_test_vhost.conf</strong></p>
<pre><code><VirtualHost 127.0.0.12:80>
ServerName apache-test.local
ServerAdmin root@localhost
DocumentRoot "/var/www/apache-test.local/public"
ErrorLog "/var/www/apache-test.local/logs/error.log"
CustomLog "/var/www/apache-test.local/logs/access.log" common
<Directory "/var/www/apache-test.local/public">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
SetHandler application/x-httpd-php
</Directory>
</VirtualHost>
</code></pre>
<p><strong>/var/www/apache-test.local/public/.htaccess</strong></p>
<p>Just as in your question.</p>
<p><strong>/var/www/apache-test.local/public/index.php</strong></p>
<p>The PHP code above.</p>
|
sql : find the lowest amount of loan at each branch <p>what does mean by this question ? I am confused . Does it say to find the lowest amount or the branch names who have the lowest amount . Help me to figure this out .</p>
<p>My_query(finding the lowest amount) : </p>
<pre><code>select min(total_amount)
from (select branch_name ,sum(amount) as total_amount
from loan group by branch_name );
</code></pre>
<p>Thanks!</p>
| <p>I think the question is asking for the smallest loan made at each branch. In this case you can use the following query:</p>
<pre><code>SELECT branch_name,
MIN(amount) as smallest_loan
FROM loan
GROUP BY branch_name
</code></pre>
|
Firebase Retrieve Data - Could not cast value <p>First, I have checked these answers that do not help me :
<a href="https://stackoverflow.com/questions/30151782/swift-json-error-could-not-cast-value-of-type-nsarraym-0x507b58-to-nsdic">Swift JSON error, Could not cast value of type '__NSArrayM' (0x507b58) to 'NSDictionary' (0x507d74)</a></p>
<p><a href="https://stackoverflow.com/questions/36217343/get-data-from-firebase">Get data from Firebase</a></p>
<p>When retrieving data from Firebase (3.x), I have an error that occurs which is :</p>
<pre><code>Could not cast value of type '__NSArrayM' (0x10ca9fc30) to 'NSDictionary' (0x10caa0108).
</code></pre>
<p>with this code and tree :</p>
<p>Tree :</p>
<p><a href="http://i.stack.imgur.com/Nt9qn.png" rel="nofollow"><img src="http://i.stack.imgur.com/Nt9qn.png" alt="enter image description here"></a></p>
<p>Retrieving function :</p>
<pre><code>func retrievePlanes() {
print("Retrieve Planes")
ref = FIRDatabase.database().reference(withPath: "results")
ref.observe(.value, with: { snapshot in
var newItems: [Planes] = []
for item in snapshot.children {
let planesItem = Planes(snapshot: item as! FIRDataSnapshot)
newItems.append(planesItem)
}
self.planes = newItems
self.tableView.reloadData()
})
}
</code></pre>
<p>Planes.swift - To manage the data</p>
<pre><code>import Foundation
import Firebase
import FirebaseDatabase
struct Planes {
let key: String!
let name: String!
let code:String!
let flightRange: Int?
let typicalSeats: Int?
let maxSeats: Int?
let wingSpan: String!
let takeoffLength: Int?
let rateClimb: Int?
let maxCruiseAltitude: Int?
let cruiseSpeed: String!
let landingLength: Int?
let engines: String!
let votes: Int?
let data: String!
let imagePlane:String!
let imageTakenFrom: String!
let ref: FIRDatabaseReference?
init(name: String, code: String, flightRange: Int, typicalSeats: Int, maxSeats: Int, wingSpan: String, takeoffLength: Int, rateClimb: Int, maxCruiseAltitude: Int, cruiseSpeed: String, landingLength: Int, engines: String, votes: Int, data: String, imagePlane: String, imageTakenFrom: String, key: String = "") {
self.key = key
self.name = name
self.code = code
self.flightRange = flightRange
self.typicalSeats = typicalSeats
self.maxSeats = maxSeats
self.wingSpan = wingSpan
self.takeoffLength = takeoffLength
self.rateClimb = rateClimb
self.maxCruiseAltitude = maxCruiseAltitude
self.cruiseSpeed = cruiseSpeed
self.landingLength = landingLength
self.engines = engines
self.votes = votes
self.data = data
self.imagePlane = imagePlane
self.imageTakenFrom = imageTakenFrom
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
ref = snapshot.ref
key = snapshot.key
let snapshotValue = snapshot.value as! [String:AnyObject]
name = snapshotValue["name"] as! String
code = snapshotValue["code"] as! String
flightRange = snapshotValue["intFlightRange"] as? Int
typicalSeats = snapshotValue["intTypicalSeats"] as? Int
maxSeats = snapshotValue["intMaxSeats"] as? Int
wingSpan = snapshotValue["wingSpan"] as! String
takeoffLength = snapshotValue["intTakeoffLength"] as? Int
rateClimb = snapshotValue["intRateClimb"] as? Int
maxCruiseAltitude = snapshotValue["intMaxCruiseAltitude"] as? Int
cruiseSpeed = snapshotValue["cruiseSpeed"] as! String
landingLength = snapshotValue["intLandingLength"] as? Int
engines = snapshotValue["engines"] as! String
votes = snapshotValue["votes"] as? Int
data = snapshotValue["data"] as! String
imagePlane = snapshotValue["planeImage"] as! String
imageTakenFrom = snapshotValue["imageTakenFrom"] as! String
}
</code></pre>
<p>on the line : <code>let snapshotValue = snapshot.value as! [String:AnyObject]</code></p>
<p>I suppose that is due to the snapshot value that can't be retrieved under <code>[String:AnyObject]</code> because of the <code>Int</code> below.
(It is working when I only have <code>String</code> in another case).</p>
<p>I also know that Firebase "converts" the JSON tree to these objects <a href="https://www.firebase.com/docs/ios/guide/understanding-data.html#section-its-json" rel="nofollow">[link]</a>:</p>
<ul>
<li><code>NSString</code></li>
<li><code>NSNumber</code></li>
<li><code>NSArray</code></li>
<li><code>NSDictionnary</code></li>
</ul>
<p>but I can't figure out what has to be changed in the snapshot.value line to make it work.</p>
<p>Thanks for your help.</p>
<p><strong>EDIT : I just sent a troubleshooting request. Will post updates.</strong>
<strong>EDIT 2: See Jay's answer. In my case the tree was wrong.</strong></p>
| <p>I took your code and shrunk it down a bit for testing, and it's working. (note Firebase 2.x on OS X and Swift 3 but the code is similar)</p>
<p>Firebase structure:</p>
<pre><code> "what-am" : {
"results" : [ {
"code" : "738/B738",
"data" : "Boeing",
"engines" : "Rolls"
}, {
"code" : "727/B727",
"data" : "Boeing",
"engines" : "Pratt"
} ]
}
</code></pre>
<p>Here's the Planes struct</p>
<pre><code>struct Planes {
var code:String!
var data: String!
var engines: String!
init(code: String, data: String, engines: String ) {
self.code = code
self.data = data
self.engines = engines
}
init(snapshot: FDataSnapshot) {
let snapshotValue = snapshot.value as! [String:AnyObject]
code = snapshotValue["code"] as! String
data = snapshotValue["data"] as! String
engines = snapshotValue["engines"] as! String
}
}
</code></pre>
<p>and then the code that reads in two planes, populates and array and then prints the array.</p>
<pre><code>let ref = self.myRootRef.child(byAppendingPath: "what-am/results")!
ref.observe(.value, with: { snapshot in
if ( snapshot!.value is NSNull ) {
print("not found")
} else {
var newItems: [Planes] = []
for item in (snapshot?.children)! {
let planesItem = Planes(snapshot: item as! FDataSnapshot)
newItems.append(planesItem)
}
self.planes = newItems
print(self.planes)
}
})
</code></pre>
<p>and finally the output</p>
<pre><code>[Swift_Firebase_Test.Planes(code: 738/B738, data: Boeing, engines: Rolls),
Swift_Firebase_Test.Planes(code: 727/B727, data: Boeing, engines: Pratt)]
</code></pre>
<p>Key and name are nil as I removed then from the Planes structure.</p>
<p>The line you asked about</p>
<pre><code>let snapshotValue = snapshot.value as! [String:AnyObject]
</code></pre>
<p>is valid as the snapshot contains a series of key:value pairs so String:AnyObject works.</p>
<p>This line changed due to Swift 3</p>
<pre><code>for item in (snapshot?.children)!
</code></pre>
<p>but other than that, the code works.</p>
<p>Try this to ensure you are reading the correct node. This reads the above structure and prints out each engine type. (tested and works)</p>
<pre><code> let ref = self.myRootRef.child(byAppendingPath: "what-am/results")!
ref.observe(.value, with: { snapshot in
if ( snapshot!.value is NSNull ) {
print("not found")
} else {
for child in (snapshot?.children)! {
let snap = child as! FDataSnapshot
let dict = snap.value as! [String: String]
let engines = dict["engines"]
print(engines!)
}
}
})
</code></pre>
|
Swift 3 Core Data "Entity" error: `Use of undeclared type` <p><code>Use of undeclared type 'Transcription'</code></p>
<p>I'm following this simple tutorial of Core Data in Swift 3 (<a href="https://learnappdevelopment.com/uncategorized/how-to-use-core-data-in-ios-10-swift-3/" rel="nofollow">https://learnappdevelopment.com/uncategorized/how-to-use-core-data-in-ios-10-swift-3/</a>)</p>
<p>and I get the above error on the line: <code>let fetchRequest: NSFetchRequest<Transcription> = Transcription.fetchRequest()</code> </p>
<p>I double checked and the Entity "Transcription" is spelled correctly in my .xcdatamodeld file</p>
<p>The tutorial was designed for Swift 3, but there was another change since it was released that I fixed, so I'm guessing some other change to Swift in the past 2 months has caused this error.</p>
<p>I'm brand new to Core Data, so I don't know how to debug this. I'd be very grateful for a solution!</p>
| <p>Highlight the Data Model, go to Editor -> Create NSManagedObject Subclass...</p>
<p>This solved the error</p>
|
merge two lists of dictionaries in python? <p>I have two lists of dictionaries:</p>
<pre><code>old = [{'a':'1','b':'2'},{'a':'2','b':'3'},{'a':'3','b':'4'},{'a':'4','b':'5'}]
new = [{'a':'1','b':'100'},{'a':'2','b':'100'},{'a':'5','b':'6'}]
</code></pre>
<p>How can I merge two lists of dictionaries to get:</p>
<pre><code>update = [{'a':'1','b':'2,100'},{'a':'2','b':'3,100'},{'a':'3','b':'4'},{'a':'4','b':'5'},{'a':'5','b':'6'}]
</code></pre>
<p>the idea is if new 'a' is not in the old, add it and if new 'a' is in the old, update 'b' and if old 'a' is not in the new, keep it.</p>
| <p>If 'a' is the real key here and b is the value, imo it would be easier to convert the list of dicts into one dict, process the merge and then convert it back. This way you can use the standard functions.</p>
<p>Convert into one dict where a is the key:</p>
<pre><code>def intoRealDict(listOfDicts):
values = []
for item in listOfDicts:
values.append((item.get('a'), item.get('b')))
return dict(values) #Use Dict Constructur ('3', '4) -> {'3': '4'}
</code></pre>
<p>Convert into the data structure again:</p>
<pre><code>def intoTheDataStructure(realDict):
res = []
for i in realDict:
res.append(dict([('a', i), ('b', realDict[i])]))
return res
</code></pre>
<p>Easy Merge of your two lists: </p>
<pre><code>def merge(l1, l2):
d1, d2 = intoRealDict(l1), intoRealDict(l2)
for i in d2:
if i in d1:
#extend "b"
d1[i] = d1[i] + ", " + d2[i]
else:
#append value of key i
d1[i] = d2[i]
return intoTheDataStructure(d1)
</code></pre>
<p>Working Code with bad performance</p>
|
Change structure of object in JavaScript <p>I have some data</p>
<pre><code>arr = {
'a': ['1', '2', '3'],
'b': ['2', '3', '4'],
'c': ['3', '5', '6'],
}
</code></pre>
<p>How can I change this to</p>
<pre><code>newArr = {
'1': ['a'],
'2': ['a', 'b'],
'3': ['a', 'b', 'c'],
'4': ['b'],
'5': ['c'],
'6': ['c']
}
</code></pre>
<p>Would the most efficient way to do something like this</p>
<pre><code>const newData = {};
Object.keys(oldData).forEach(key => {
newData[key].forEach(value => {
if (!newData[value]) {
newData[value] = [];
}
newData[value].push(key);
});
});
</code></pre>
<p>Wouldn't it be quite easy with ES6, maybe using <code>reduce()</code>?</p>
| <p>Just change one line</p>
<pre><code>newData[key].forEach(value => {
</code></pre>
<p>to</p>
<pre><code>oldData[key].forEach(value => {
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var oldData = {
'a': ['1', '2', '3'],
'b': ['2', '3', '4'],
'c': ['3', '5', '6'],
};
const newData = {};
Object.keys(oldData).forEach(key => {
oldData[key].forEach(value => {
// ^^^^^^ change to oldData instead of newData
if (!newData[value]) {
newData[value] = [];
}
newData[value].push(key);
});
});
console.log(newData);</code></pre>
</div>
</div>
</p>
|
spring security - how to provide a list of intercepting URL's <p>In my spring project having a bunch of users and User Levels. so that need to provide a list of intercepting url's and its access control. currently it is written in spring security xml file. how can i make it simple to do?</p>
<p>any suggestions will be appreciated </p>
| <p>May be if you want to put them in application properties, then use WebSecurityConfigurerAdapter</p>
<p>in <strong>application.properties</strong></p>
<pre><code>url1 = /admin
url2 = /reservation/**
</code></pre>
<p>===</p>
<pre><code>@Configuration
@EnableWebSecurity
@PropertySource("classpath:application.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${url1}")
private String url1;
@Value("${url1}")
private String url2;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//..
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(url1).access("hasRole('ROLE_ADMIN')")
.antMatchers(url2).access("hasRole('ROLE_USER') ;
}
}
</code></pre>
|
jquery add event to cells into a board <p>How can I add an event to cells inside a board?
I have a grid of 9x9 and I want to add an event to them, for example, this is part of my grid in HTML:</p>
<pre><code><div class="container">
<div class="dad-board">
<div class="dad-row">
<div class="dad-cell">
<input type="number" data-column="0" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="1" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="2" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="3" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="4" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="5" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="6" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="7" data-line="0">
</div>
<div class="dad-cell">
<input type="number" data-column="8" data-line="0">
</div>
...
</div>
</div>
</code></pre>
<p>Now in jquery I wanted to do something like this:</p>
<pre><code>(function() {
'use strict'
$('#dad-board > dad-cell').focusout(function(){
if($(this).text()>0 && $(this).text()<10){
$(this).addClass('with-value');
}else{
$(this).removeClass('with-value');
}
});
}());
</code></pre>
| <p>Two things:</p>
<p>In <code>$('#dad-board > dad-cell')</code> the class name should be <code>.dad-cell</code>.</p>
<p><code>.dad-cell</code> are <code>div</code> and as such them don't have a <code>focusout</code> event. I think you meant <code>$('#dad-board > .dad-cell input')</code>.</p>
<p>In order to make your current code work, you'll also have to make some adjustments:</p>
<pre><code>$('#dad-board > .dad-cell input').focusout(function(){
//as we're talking about input fields, the value is read with val(), not text()
//and as you're gonna evaluate it as an integer, lets convert the value to integer
var value=parseInt($(this).val());
if(!isNaN(value)&&value>0 && value<10){
//you might want to set with-value to the <div>, not the input
$(this).parent().addClass('with-value');
}else{
//you might want to set with-value to the <div>, not the input
$(this).parent().removeClass('with-value');
}
});
</code></pre>
|
Use of deleted copy constructor in the singleton <p>I've implemented the singleton pattern like <a href="http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104">this</a>, there is my code:</p>
<p><strong>header file:</strong></p>
<pre><code>class Settings_manager{
public:
static Settings_manager& get_instance();
void operator=(Settings_manager const&) =delete;
Settings_manager(Settings_manager const&) =delete;
...
private:
Settings_manager();
};
</code></pre>
<p><strong>implementation:</strong></p>
<pre><code>Settings_manager& Settings_manager::get_instance()
{
static Settings_manager instance;
return instance;
}
Settings_manager::Settings_manager()
{
read_file();
}
</code></pre>
<p>When I try use <code>get_instance</code> function in <code>main</code> like this:</p>
<pre><code>Settings_manager set = Settings_manager::get_instance();
</code></pre>
<p>or <code>Settings_manager set = std::move(Settings_manager::get_instance());</code></p>
<p>I get </p>
<pre><code>error: use of deleted function 'Settings_manager::Settings_manager(const Settings_manager&)'
Settings_manager set = Settings_manager::get_instance();
</code></pre>
<p>Can somebody tell, what's wrong and explain it? Thanks.</p>
| <p>Consider what you're trying to do here:</p>
<pre><code>Settings_manager set = Settings_manager::get_instance();
</code></pre>
<p>You have your singleton, <code>get_instance()</code>, and you're trying to copy it? That would kind of defeat the purpose of singleton if you could just... create two of them right?</p>
<p>You want to take a <em>reference</em>:</p>
<pre><code>Settings_manager& set = Settings_manager::get_instance();
</code></pre>
<p>This way, <code>set</code> <em>is</em> the singleton instance. Not a copy of it. </p>
|
Dagger 2: Providing dependencies in Application Module vs injecting them <p>I was trying to add Dagger 2 to my android app.
As far as I understand, Dagger will construct my object(which I am trying to inject) as long as its' dependencies are provided(in a Module) or they are injected using some form of injection(constructor/method).</p>
<p>I would like to know if there's a distinction between when a dependency should be provided in a Module(say Application Module) vs when its' injected using a constructor injection, and if there is any rule of when I should do which?</p>
| <p>Both are the same. Constructor injection basically eliminates the need to write a provider method. As a rule of thumb, I mostly use it for classes with a no-args constructor for easy injection, like Util classes. </p>
|
Yii2 GridView how to display column only when some filter is active <p>I have a Yii2 GridView with implemented sortable option (I used <a href="https://github.com/kotchuprik/yii2-sortable-widgets" rel="nofollow">kotchuprik extension</a>) which add one column with drag'n'drop ability. The problem is that I need to be able to sort rows when some filter id GridView is set. GridView have column "Machine ID" and sorting need to be done only with rows with the same "Machine ID", so how to display column with drag'n'drop ability only when some Machine ID is set by column filter??</p>
| <p>You could use the visible property of the column </p>
<p>Yii\grid\DataColumn has visible property.
This attrribute accepts boolean values,
but you can dynamically using an expression that boolean value. eg:</p>
<pre><code> use Yii;
...
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'tipo',
['attribute' => 'your_attribute',
'label' => 'Your Label',
'visible' => isThisColumnVisible(),
],
</code></pre>
<p><a href="http://www.yiiframework.com/doc-2.0/yii-grid-column.html#" rel="nofollow">http://www.yiiframework.com/doc-2.0/yii-grid-column.html#</a>$visible-detail</p>
<p>You can check $searchModel->your_attribute or a equivalent functin that return boolean </p>
<pre><code> 'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'tipo',
['attribute' => 'your_attribute',
'label' => 'Your Label',
'visible' => isset($searchModel->your_attribute) ,
],
</code></pre>
|
Function.prototype does not show all in-built properties and methods in console <p>This <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype" rel="nofollow">MDN article</a> on <code>Function.prototype</code> objects lists native properties and methods however when I echo <code>Function.prototype</code> in Firefox or Chrome's console, it outputs <code>"function () { }"</code>.</p>
<p>Why does not it output all the properties and methods as listed on MDN article? </p>
| <p>This is simply how the browser decides to "show" you the object, because reasons.</p>
<p>In Chrome you can do <code>dir(Function.prototype)</code> and it will list all methods and properties of the object. Firefox may have something similar.</p>
<p>UPDATE: In Firefox you can simply right click on what it shows you when you do <code>Function.prototype</code> and select "Open in variables view" where it will list you all properties and methods.</p>
|
Mine Tweets between two dates in Python <p>I would like to mine tweets for two keywords for a specific period of time. I currently have the code below, but how do I add so it only mine tweets between two dates? (10/03/2016 - 10/07/2016) Thank you!</p>
<pre><code>#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['python', 'javascript', 'ruby'])
</code></pre>
| <p>You can't. Have a look at <a href="http://stackoverflow.com/questions/26205102/making-very-specific-time-requests-to-the-second-on-twitter-api-using-python">this question</a>, that is the closest you can get.</p>
<p>The Twitter API does not allow to search by time. Trivially, what you can do is fetching tweets and looking at their timestamps afterwards in Python, but that is highly inefficient.</p>
|
How to use JGit to get list of changes in files? <p>Using JGit, I want to get a list of changes in files of a commits as is possible with <code>git log --full-history -p -1 <hash-id></code>.</p>
<p>Is this possible? If so, how do you do it?</p>
<p>I know how to get each commit, and look at the commit message: </p>
<pre><code>//Load repo
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repo = builder.setGitDir(new File("/path/to/repo/.git")).setMustExist(true).build();
Git git = new Git(repo);
//get commits
Iterable<RevCommit> log = git.log().call();
for (RevCommit commit : log) {
//Shows the hashid
System.out.println("LogCommit: " + commit);
//Shows only commit message
String logMessage = commit.getFullMessage();
System.out.println("LogMessage: " + logMessage);
}
git.close();
</code></pre>
<p>What allows me to get the changes in the files?</p>
<p>For example I write:</p>
<pre><code>git log --full-history -p -1 8309c1262e1b7ffce8fc86efc1ae5777a4a96777
</code></pre>
<p>The response is</p>
<pre><code>commit 8309c1262e1b7ffce8fc86efc1ae5777a4a96777
Author: <redacted>
Date: Thu Aug 4 12:15:23 2016 -0400
Fixed typo in commit
diff --git a/Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/messaging/server/BaseService.java b/Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/messaging/server/BaseService.java
index fa55e7e..4f3c155 100644
--- a/Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/messaging/server/BaseService.java
+++ b/Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/messaging/server/BaseService.java
@@ -56,6 +57,7 @@ public abstract class BaseService {
protected AssertionType getAssertion(WebServiceContext context, AssertionType assertionIn) {
AssertionType assertion;
- WSAHeaderHelper wsaHlpr = new WSAHeaderHelper();
+ WSAHeaderHelper wsaHelper = new WSAHeaderHelper();
if (assertionIn == null) {
assertion = SAML2AssertionExtractor.getInstance().extractSamlAssertion(context);
</code></pre>
<p>I want to have something like the following. Change is a made up class:</p>
<pre><code>//Load repo
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repo = builder.setGitDir(new File("/path/to/repo/.git")).setMustExist(true).build();
Git git = new Git(repo);
//get commits
Iterable<RevCommit> log = git.log().call();
for (RevCommit commit : log) {
//Shows the hashid
System.out.println("LogCommit: " + commit);
//Shows only commit message
String logMessage = commit.getFullMessage();
System.out.println("LogMessage: " + logMessage);
List<Change> changes = commit.getChanges();
for(Change change: changes):
System.out.println("File: " + change.getFile());
System.out.println("Change: " + change.getChange());
System.out.println("ChangeType: " + change.getChangeType());
}
git.close();
</code></pre>
<p>The output would look something like:</p>
<pre><code>LogCommit: 8309c1262e1b7ffce8fc86efc1ae5777a4a96777
LogMessage: Fixed typo in commit
File: Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/messaging/server/BaseService.java
Change: WSAHeaderHelper wsaHlpr = new WSAHeaderHelper();
ChangeType: D
File: Product/Production/Common/CONNECTCoreLib/src/main/java/gov/hhs/fha/nhinc/messaging/server/BaseService.java
Change: WSAHeaderHelper wsaHelper = new WSAHeaderHelper();
ChangeType: A
</code></pre>
| <p>JGit has a very simple <code>diff</code> command that would write textual diff of the changes between two commits to an output stream.</p>
<p>For example:</p>
<pre class="lang-java prettyprint-override"><code>OutputStream outputStream = ...
List<DiffEntry> diffEntries = git.diff().setOutputStream( outputStream ).call();
</code></pre>
<p>Probably more interesting is the list of <code>DiffEntry</code> returned after calling the command.
Each DiffEntry represents a changed files and tells its path name, whether it was added, changed or deleted, pointers (blob-ids's) to the old and new content and more.</p>
<p>And from each <code>DiffEntry</code>, you can obtain an <code>EditList</code> which holds information about which lines were changed.</p>
<p>For Example:</p>
<pre class="lang-java prettyprint-override"><code>try( DiffFormatter diffFormatter = new DiffFormatter( DisabledOutputStream.INSTANCE ) ) {
diffFormatter.setRepository( git.getRepository() );
List<DiffEntry> diffEntries = diffFormatter.scan( oldTreeIterator, newTreeIterator );
FileHeader fileHeader = diffFormatter.toFileHeader( diffEntries.get( 0 ) );
return fileHeader.toEditList();
}
</code></pre>
<p>This code also shows how to obtain diff entries with more detailed control without using the <code>DiffCommand</code>.</p>
<p>Just recently I wrote an entire blog post about JGit's diff APIs. For more details please see here: <a href="http://www.codeaffine.com/2016/06/16/jgit-diff/" rel="nofollow">http://www.codeaffine.com/2016/06/16/jgit-diff/</a></p>
|
ContentCachingResponseWrapper Produces Empty Response <p>I'm trying to implement filter for logging requests and responses in <code>Spring MVC</code> application.
I use the following code:</p>
<pre><code>@Component
public class LoggingFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
LOGGER.debug(REQUEST_MESSAGE_FORMAT, requestWrapper.getRequestURI(), requestWrapper.getMethod(), requestWrapper.getContentType(),
new ServletServerHttpRequest(requestWrapper).getHeaders(), IOUtils.toString(requestWrapper.getInputStream(), UTF_8));
filterChain.doFilter(requestWrapper, responseWrapper);
LOGGER.debug(RESPONSE_MESSAGE_FORMAT, responseWrapper.getStatus(), responseWrapper.getContentType(),
new ServletServerHttpResponse(responseWrapper).getHeaders(), IOUtils.toString(responseWrapper.getContentInputStream(), UTF_8));
}
}
</code></pre>
<p>So, I get my request and respone logged as expected. Here are the logs:</p>
<pre><code>2016-10-08 19:10:11.212 DEBUG 11072 --- [qtp108982313-19] by.kolodyuk.logging.LoggingFilter
----------------------------
ID: 1
URI: /resources/1
Http-Method: GET
Content-Type: null
Headers: {User-Agent=[curl/7.41.0], Accept=[*/*], Host=[localhost:9015]}
Body:
--------------------------------------
2016-10-08 19:10:11.277 DEBUG 11072 --- [qtp108982313-19] by.kolodyuk.logging.LoggingFilter
----------------------------
ID: 1
Response-Code: 200
Content-Type: application/json;charset=UTF-8
Headers: {}
Body: {"id":"1"}
--------------------------------------
</code></pre>
<p>However, the empty response is returned. Here's the output from <code>curl</code>:</p>
<pre><code>$ curl http://localhost:9015/resources/1 --verbose
* Trying ::1...
* Connected to localhost (::1) port 9015 (#0)
> GET /resources/1 HTTP/1.1
> User-Agent: curl/7.41.0
> Host: localhost:9015
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sat, 08 Oct 2016 17:10:11 GMT
< Content-Type: application/json;charset=UTF-8
< Content-Length: 0
<
* Connection #0 to host localhost left intact
</code></pre>
<p>Any ideas?</p>
<p>Thanks</p>
| <p>After couple of houurs of struggling, I've finally found the solution.</p>
<p>In short, <code>ContentCachingResponseWrapper.copyBodyToResponse()</code> should be called in the end of the filter method.</p>
<p><code>ContentCachingResponseWrapper</code> caches the response body by reading it from response output stream. So, the stream becomes empty. To write response back to the output stream <code>ContentCachingResponseWrapper.copyBodyToResponse()</code> should be used.</p>
|
PDO fetch returns only first row <p><strong>UPDATE 2:</strong>
I kindly asked to unmark this question as duplicate as it is not a duplicate of the other question, which after some research I discovered the problem and provided an effective answer, which the person that marked my question as duplicate didn't provide stating that the code worked for him. Well, it is working for him, but it is not working for me. I also read many many questions where when someone tests the code and it works for him, he just puts a note in the comments like this "<em>It works for me</em>", or something similar. And instead of marking my question and later posting the following comment:</p>
<p>"<em>what you should have done, was edit your other question, rather than reposting with the same code. Sorry, but I won't be reopening the question. I posted a few comments under your other question yesterday but didn't bother replying so I ended up deleting them. Stating that there was nothing wrong with your code since I tested it.</em>"</p>
<p>.. maybe what he should do is just advice in the comments and most probably I could have edited both of my questions, instead of having to "argue" and complain just because I want to delete my question, which is now impossible, and if I post another question, it will obviously get marked as a Duplicate too. This is just very unfortunate.
Also I don't see this - <strong>PDO fetch returns only first row</strong> as a duplicate of this <strong>PHP PDO Data_length always returns â0â</strong></p>
<p><strong>ORIGINAL QUESTION:</strong>
I'm using the following code to make a connection to the database, fetch the <code>Data_length</code> index column, and calculate the database size based on the data.</p>
<p>For some reason PDO will always return "0", which is the value for the <code>Data_length</code> index in the first row. Whatever I do, I only get the first rows index.</p>
<p>The database is MySQL, the engine MyISAM. </p>
<p>PHP Version: 5.5.38<br>
MySQL Version: 5.5.50</p>
<p><strong>UPDATE 1:</strong>
Well, as this question was marked a duplicate from <a href="http://stackoverflow.com/questions/39932806/php-pdo-data-length-always-returns-0">this</a> one, I was forced to change the source code. The following is the new source code which is working fine on one hosting, but still returns only the first row on another.</p>
<pre><code>// START GET DATABASE SIZE
// Connect to database
$conn = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
// Execute query
$stmt = $conn->query('SHOW TABLE STATUS');
// Get size from array
$size = $stmt->fetch(PDO::FETCH_ASSOC)["Data_length"];
// Set values to variables for use
$decimals = 4;
$mbytes = round($size/(1024*1024),$decimals);
$kilobytes = round(($size / 1024) * 10);
echo $kilobytes;
// END GET DATABASE SIZE
</code></pre>
<p><strong>The old source code:</strong>
I have copied this code from <a href="http://stackoverflow.com/questions/21487673/php-pdo-retreive-mysql-db-size">this answer</a> as it was accepted as working. I couldn't comment there as I don't have enough reputation.</p>
<pre><code><!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<?php
try {
error_reporting(-1);
$host_name = "my_host";
$database = "my_db";
$user_name = "my_user";
$password = "my_pwd";
$conn = new PDO("mysql:host=$host_name;dbname=$database", $user_name, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->query('SHOW TABLE STATUS');
$dbSize = 0;
$row = $sth->fetch(PDO::FETCH_ASSOC);
$dbSize = $row["Data_length"];
$decimals = 2;
$mbytes = round($dbSize/(1024*1024),$decimals);
echo $dbSize . "\n" . $row["Data_length"];
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
</body>
</html>
</code></pre>
| <p>Add a while loop,</p>
<pre><code>while($row= $sth->fetch( PDO::FETCH_ASSOC )){
echo $row['your_field_name'];
}
</code></pre>
<p>Or you can use <code>fetchAll</code></p>
<pre><code>$row= $sth->fetchAll();
print_r($row);
</code></pre>
|
C++ problems in vector usage <p>Let's say I input values between 0-109 several times. I have a vector that counts how many times a value in a specific range(0-9, 10-19,...100-109) has occurred. </p>
<p>For instance, my vector initially: </p>
<p>0 0 0 0 0 0 0 0 0 0 0</p>
<p>I give 15, 16, 88, 95, 94, 5 as input.Vector becomes: </p>
<p>1 2 0 0 0 0 0 0 1 2 0</p>
<p>Here is my code: </p>
<pre><code>#include <iostream>
#include <vector>
using std::vector; using std::endl;
using std::cin; using std::cout;
int main()
{
int m=0;
vector<int>vec(11,0);//00000000000
while(cin>>m)
{
vec[m/10]=vec[m/10]+1;//ex: m=15->m/10==1->vec[1]=vec[1]+1->vec[1]==1;
}//use ctrl+z(windows) to break
cout<<"012345678910"<<endl;
for(decltype(vec.size()) i:vec)
{
cout<<vec[i];
}
}
</code></pre>
<p>Why my code doesn't work correctly?</p>
<p>P.S. Code tends to use one value for many elements of vector. </p>
| <p>This is not want you expect:</p>
<pre><code>for(decltype(vec.size()) i:vec)
{
cout<<vec[i];
}
</code></pre>
<p>A range based for gives you element values, not element indices.</p>
<p>You likely want:</p>
<pre><code>for(const auto& e : vec)
{
cout<<e;
}
</code></pre>
|
Laravel: Can't access Eloquent relationship <p>I've made Post and User models and defined a one to many relationship between the two like so:</p>
<p><strong>User.php</strong></p>
<pre><code><?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'profile_picture',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts () {
return $this->hasMany(Post::class,'post_author');
}
}
</code></pre>
<p><strong>Post.php</strong></p>
<pre><code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'post_title', 'post_content', 'post_author', 'post_type', 'created_at', 'updated_at',
];
public function user() {
return $this->belongsTo(User::class,'id');
}
public function postfields() {
return $this->hasMany(PostField::class);
}
}
</code></pre>
<p>Now, in my blog controller I compact the Post class into my blog view like so:</p>
<p><strong>BlogController.php</strong></p>
<pre><code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\User;
class BlogController extends Controller
{
public function index(Post $post) {
$blog_posts = Post::with('user')->where('post_type', '=', 'blog')->get();
return view('blog', compact('blog_posts'));
}
}
</code></pre>
<p>Now I attempt to access the relationship inside of the blog view:</p>
<pre><code>@foreach ($blog_posts as $blog_post)
<div class="post item">
{{ $blog_post->post_title }}
{{ $blog_post->post_content }}
{{ $blog_post->user->name }}
</div>
@endforeach
</code></pre>
<p>Everything appears as it should in the blog view when there is only one blog post in the database, however I get the following error when there is more than one:</p>
<p>ErrorException in 84794846d554b14eb937f08dfef09b6f1edd91c6.php line 43:
Trying to get property of non-object (View: C:\MAMP\htdocs\Biota-New\resources\views\blog.blade.php)</p>
<p>Any help would be much appreciated.</p>
<p>Here's a DD of the $blog_posts variable:</p>
<pre><code>Collection {#198 â¼
#items: array:2 [â¼
0 => Post {#194 â¼
#fillable: array:6 [â¼
0 => "post_title"
1 => "post_content"
2 => "post_author"
3 => "post_type"
4 => "created_at"
5 => "updated_at"
]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:7 [â¼
"id" => 1
"post_title" => "TEST"
"post_content" => "Test post"
"post_author" => 1
"post_type" => "blog"
"created_at" => "2016-10-08 14:20:07"
"updated_at" => "2016-10-08 14:20:07"
]
#original: array:7 [â¼
"id" => 1
"post_title" => "TEST"
"post_content" => "Test post"
"post_author" => 1
"post_type" => "blog"
"created_at" => "2016-10-08 14:20:07"
"updated_at" => "2016-10-08 14:20:07"
]
#relations: array:1 [â¼
"user" => User {#199 â¼
#fillable: array:4 [â¼
0 => "name"
1 => "email"
2 => "password"
3 => "profile_picture"
]
#hidden: array:2 [â¼
0 => "password"
1 => "remember_token"
]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:9 [â¼
"id" => 1
"name" => "Sup3rL3on"
"email" => "codeoncaffeine1@gmail.com"
"password" => "$2y$10$b6pMtiKt0LcDCeRtTlVJzOL3BvD6Ru1TihbOhM7FOHUscW0daIwGC"
"profile_picture" => "default-profile-picture"
"account_type" => 1
"remember_token" => null
"created_at" => null
"updated_at" => null
]
#original: array:9 [â¼
"id" => 1
"name" => "Sup3rL3on"
"email" => "codeoncaffeine1@gmail.com"
"password" => "$2y$10$b6pMtiKt0LcDCeRtTlVJzOL3BvD6Ru1TihbOhM7FOHUscW0daIwGC"
"profile_picture" => "default-profile-picture"
"account_type" => 1
"remember_token" => null
"created_at" => null
"updated_at" => null
]
#relations: []
#visible: []
#appends: []
#guarded: array:1 [â¼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [â¼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
1 => Post {#195 â¼
#fillable: array:6 [â¼
0 => "post_title"
1 => "post_content"
2 => "post_author"
3 => "post_type"
4 => "created_at"
5 => "updated_at"
]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:7 [â¼
"id" => 6
"post_title" => "TEST"
"post_content" => "Test post"
"post_author" => 1
"post_type" => "blog"
"created_at" => "2016-10-08 14:20:07"
"updated_at" => "2016-10-08 14:20:07"
]
#original: array:7 [â¼
"id" => 6
"post_title" => "TEST"
"post_content" => "Test post"
"post_author" => 1
"post_type" => "blog"
"created_at" => "2016-10-08 14:20:07"
"updated_at" => "2016-10-08 14:20:07"
]
#relations: array:1 [â¼
"user" => null
]
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [â¼
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
}
</code></pre>
<p><strong>Blog.blade.php</strong></p>
<pre><code>@extends('layouts.front-header')
@section('content')
<style>
.hero-image {
background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url(images/hero-2.jpg);
}
</style>
<div class="hero-image hero-image-inner-page">
<div class="hero-image-inner">
<div class="text">
<h1>Blog</h1>
</div>
</div>
</div>
<main>
<section class="blog">
<div class="container">
<div class="posts">
<div class="items">
<!--
<div class="post item">
<h3 data-field="post_title"></h3>
<p data-field="post_content"></p>
<img src="http://fiddle-earth.com/updates/madsa/img/image00.png" alt="">
<div class="post-data">
<img data-field="author_profile_picture" alt="">
<p>posted by <strong data-field="post_author"></strong> on <span data-field="post_date"></span></p>
</div>
</div> -->
@foreach ($blog_posts as $blog_post)
<div class="post item">
<h3 data-field="post_title">{{ $blog_post->post_title }}</h3>
<p data-field="post_content">{{ $blog_post->post_content }}</p>
<!-- <img src="http://fiddle-earth.com/updates/madsa/img/image00.png" alt=""> -->
<div class="post-data">
<img data-field="author_profile_picture" alt="">
@if($blog_post->user()!=null)
{{ $blog_post->user->name }}
@endif
<p>posted by <strong data-field="post_author"></strong> on <span data-field="post_date"></span></p>
</div>
</div>
@endforeach
</div>
<!-- <a href="#" class="items-load">Load more</a> -->
</div>
</div>
</section>
</main>
<script src="assets/js/loadmore.js"></script>
<script>
$('.posts').loadmore({
source: 'assets/js/json/blog-json.php',
img: 'uploads/',
step: 4
});
</script>
@endsection
</code></pre>
| <p>As far as I can see, the <code>User</code> relation in the Post model is causing the exception. So, when you call:</p>
<pre><code>{{ $blog_post->user->name }}
</code></pre>
<p>it can't find the user associated with that post. I am guessing that the foreign key for <code>User</code> table is not the same as <a href="https://laravel.com/docs/5.3/eloquent-relationships#one-to-many-inverse" rel="nofollow" title="guessed">guessed</a> by Laravel:</p>
<blockquote>
<p>Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Comment model is not post_id, you may pass a custom key name as the second argument to the belongsTo method:</p>
</blockquote>
<pre><code>public function post()
{
return $this->belongsTo('App\Post', 'foreign_key');
}
</code></pre>
<p>So in your case, it would be something like this:</p>
<pre><code>public function user()
{
return $this->belongsTo('App\User', 'post_user_id'); //Replace post_user_id with the id convention you are using.
}
</code></pre>
<p><s><strong>Update:</strong></s></p>
<p><s>Thanks for the dd on your $blog_posts. I can see that the user is being fetched but it's not being called correctly. It's a function so you need to treat it as a function. Modify your blade file to retrieve the user like this:</p>
<pre><code>{{ $blog_post->user()->name }}
</code></pre>
<p>This should get the valid user collection.</s></p>
<p><s><strong>Update 2:</strong></p>
<p>As I can see from the dump, the user relation from the second <code>Post</code> is null. Make sure it's not null when you are creating the post and to deal with it in the blade, wrap it in a null check:</p>
<pre><code>@foreach ($blog_posts as $blog_post)
<div class="post item">
{{ $blog_post->post_title }}
{{ $blog_post->post_content }}
@if($blog_post->user()!=null)
{{ $blog_post->user()->name }}
@endif
</div>
@endforeach
</code></pre>
<p></s>
<strong>Update 3:</strong></p>
<p>It actually is supposed to be called as an attribute rather than a function since it returns 'BelongsTo' when called as a function. Try the following now:</p>
<pre><code>@foreach ($blog_posts as $blog_post)
<div class="post item">
{{ $blog_post->post_title }}
{{ $blog_post->post_content }}
@if($blog_post->user!=null)
{{ $blog_post->user->name }}
@endif
</div>
@endforeach
</code></pre>
<p>I've reproduced the same issue here and this fixes it. Let me know if it works for you.</p>
|
openssl_private_encrypt and "error:0E06D06C...NCONF_get_string:no value" <p>I can generate all keys fine, when I go to encrypt the file I get an error thrown at me: <code>error:0E06D06C:configuration file routines:NCONF_get_string:no value</code> but googling and checking stackoverflow only shows people with problems generating the keys.
My code: <a href="http://pastebin.com/MHit3LkR" rel="nofollow">Here</a></p>
<p>EDIT: The error pops up when I put <code>or die(openssl_error_string());</code> after <code>openssl_private_encrypt($fileToEnc, $encFile, $privateKey)</code> but I am now getting <code>fwrite() expects parameter 1 to be resource, boolean given in C:\wamp\www\xr1\encrypt.php on line 9</code></p>
| <p>There was an error in my fopen dir somehow and it just broke. It is all good and fixed now, thanks.</p>
|
Qt Error while building first project[Windows] <p>I installed Qt Creator 4.1 Based on Qt 5.7.0 from <a href="https://www.qt.io/" rel="nofollow">https://www.qt.io/</a>.</p>
<p>I tried to build a Qt Widgets Application, but I got the following error in the Console output:</p>
<pre><code>Error while building/deploying project HelloWorld (kit: Desktop Qt 5.7.0 MSVC2015_64bit)
When executing step "qmake"
</code></pre>
<p>What may be causing this problem?</p>
<p>I have searched in Google, but didn't find a solution to the problem. I am using Windows 8.1 x64 if that matters.</p>
| <p>You should install visual studio 2015 or vs c++ 2015 compiler so you can use vs compiler 2015 with Qt or use Qt with MinGW compiler</p>
|
Binding object into callback using arrow function <p>I'm new to javascript and ES6. How do I bind the <code>websocket</code> object into the callback I supply to <code>subscribe</code>? It feels wrong/wierd to me that I am accessing the <code>websocket</code> object from "global" scope like this. </p>
<pre><code>const URL = 'echo.websocket.org';
const websocket = new WebSocket(`wss://${URL}`);
websocket.onmessage = (event)=>redux.dispatch(ChatActions.receiveMessage(event.data));
redux.subscribe(() => {
const { lastAction } = redux.getState();
switch (lastAction.type) {
case ActionTypes.POST_MESSAGE:
return websocket.send(lastAction.text);
default:
return;
}
});
</code></pre>
| <p>You will likely want to use a <a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" rel="nofollow">closure</a>:</p>
<pre><code>let webSocket = new WebSocket(url);
let takesWebSocket = socket => {
return () => {
// do stuff with the websocket
};
};
let subscribeCallback = takesWebSocket(webSocket);
redux.subscribe(subscribeCallback);
</code></pre>
|
UIFieldBehaviour for snapping dynamic view to top, bottom or middle of screen <p>I'm using a draggable view which is the width and height of the screen and can be moved up or down on the screen depending on the pan gesture. </p>
<p>When the pan gesture has ended I want it to snap to three different y positions, top, middle or bottom of the screen according to where the view was when the pan ended. I want something like the UIFieldBehaviour where a force is animating it to the correct position.</p>
<p>When in top the whole view will be displayed and when in the bottom only like 30px should be displayed and the rest of the view will be under the screen so to speak.
Therefore I need the force to only behave to the top 30px of the view.</p>
<p>Force field behaviour (sorry for bad painting): </p>
<p><a href="http://i.stack.imgur.com/aeWGD.png" rel="nofollow"><img src="http://i.stack.imgur.com/aeWGD.png" alt="enter image description here"></a></p>
<p>Snap behaviour:<br>
<a href="http://i.stack.imgur.com/yG6ZG.png" rel="nofollow"><img src="http://i.stack.imgur.com/yG6ZG.png" alt="enter image description here"></a></p>
<p>Any ideas on how to achieve this?</p>
| <p>It was easier than I thought.
I'm using the new UIViewPropertyAnimator and when pan .ended I just check whether the targets y-position should snap to the top, bottom or middle by comparing it to the height of the UIScreen.</p>
<pre><code> animator!.addAnimations({
print(target.frame.origin.y)
if (target.frame.origin.y > UIScreen.main.bounds.height / 2) {
if (target.frame.origin.y > (UIScreen.main.bounds.height - 50)) {
target.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 25, width: self.view.frame.width, height: self.view.frame.height)
} else {
target.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 95, width: self.view.frame.width, height: self.view.frame.height)
}
} else {
target.frame = CGRect(x: 0, y: 120, width: self.view.frame.width, height: self.view.frame.height)
}
})
animator!.startAnimation()
</code></pre>
|
AV Capture Contents of a *View* to a Movie <p>I know how to use AVFoundation to capture the contents of a <em>screen</em> to a movie file, but I'd like to instead capture the contents of an NSView instead. My app does some things in a view and currently to generate a movie file I have to record the whole screen (cropped of course). It would be much easier on the user if the app could be in the background and still be recording the session. I've considered maybe creating a fake screen and trying to reflect the contents of the view there, but that seems overcomplicated.</p>
| <p>I've had some success with a pure CALayer tree using a CARenderer into an old-style OpenGL context into a CVOpenGLTextureCache / AVAssetWriter, then also displaying it to a regular GL view or layer for display.</p>
<p>There are some quirks in the old renderer, however, so you might have to tweak things a bit to make it work with retina, etc. Haven't tried with a proper NSView tree, and the CA maintainers were surprised it worked at WWDC. So future support may be limited.</p>
<p>Seems like a good request though, I'd be happy to reference your radar.</p>
|
How to read sets of pairs from a list of integers? <p>The idea being the program would read the 4 integers submitted and would have one result if there were 2 sets of pairs and another result if otherwise. </p>
<p>For example, <code>(3, 5, 3, 5)</code> and <code>(3, 3, 3, 3)</code> would have one effect, but <code>(2, 2, 4, 5)</code> would have another. </p>
<p>All I can think of is having if statements like so: </p>
<p>if num1 == num2 == num3 == num4
print("Hello, world.")</p>
<p>for each possible condition, but I'm sure there's a better way to do so. </p>
| <p>How about:</p>
<pre><code>from collections import Counter
def has_two_pair(array):
two_most_common = Counter(array).most_common(2)
counts = [count for _, count in two_most_common if count > 1]
length = len(counts)
return length > 0 and all([(length > 1 and count > 1) or count > 3 for count in counts])
</code></pre>
<p><strong>USAGE</strong></p>
<pre><code>>>> has_two_pair((3, 5, 3, 5))
True
>>> has_two_pair((3, 3, 3, 3))
True
>>> has_two_pair((2, 2, 4, 5))
False
>>> has_two_pair(())
False
</code></pre>
<p>Likely more complex than necessary, it has the advantage that if you increase the input beyond 4 items, it should still work:</p>
<pre><code>>>> has_two_pair((1, 2, 2, 3, 3, 4))
True
>>>
</code></pre>
<p>But if four items is a hard limit, then Sven Marnach's suggested solution is a winner:</p>
<pre><code>def has_two_pair(array):
ordered = sorted(array)
return len(ordered) == 4 and ordered[0] == ordered[1] and ordered[2] == ordered[3]
</code></pre>
|
moment.js uses the month as day instead the day <p>I'm using currently moment.js (moment-with-locales.js - v.2.14.1) in my project. I want to remove the time of my datetime string to get only the date. But if I use the <code>.format()</code> method of moment.js I got an incorrect date.</p>
<p>I want to format this datetime string:</p>
<p>from ' <strong>08.10.2016 11:00</strong> ' to ' <strong>08.10.2016</strong> '</p>
<p>Here is a snipped that I used in my angular project:</p>
<pre><code>var date = moment('08.10.2016 11:00').format('DD.MM.YYYY')
console.log(date)
</code></pre>
<p>If I run this I got this output</p>
<pre><code>10.08.2016
</code></pre>
<p>instead of
08.10.2016</p>
<p>The funny thing is, if I want to get the timestamp (milliseconds) of my datetime string, it works perfect. Example:</p>
<pre><code> var dateStart = moment('08.10.2016 19:00', 'DD.MM.YYYY HH:mm').valueOf()
console.log(dateStart)
</code></pre>
<p>Will return</p>
<pre><code>1475946000000 -> Sat Oct 08 2016 19:00:00 GMT+0200
</code></pre>
<p>How can I get the correct Date?</p>
| <p>It depends on your locale. <code>en-US</code> locate means moment will parse by "month day year". So, you need to parse with the pattern as well:</p>
<pre><code>var date = moment('08.10.2016 11:00','DD.MM.YYYY HH:mm').format('DD.MM.YYYY')
</code></pre>
|
moved all models to Models folder, have now can't use attach() <p>I've decided to move all models inclusing User to Models folder and everything works except for one thing. I have a this trait</p>
<pre><code>trait Favoritable{
public function favorites()
{
return $this->belongsToMany(Album::class, 'favorites')->withTimestamps();
}
public function favorite(Album $album)
{
if(! $this->checkIfFavorited($album)){
return $this->favorites()->attach($album);
}
}
public function checkIfFavorited(Album $album)
{
return $this->favorites()->where('album_id', $album->id)->exists();
}
</code></pre>
<p>that I use in my User model class. Since I moved all models to new folder, I can't favorite an album anymore. Here is the error message that I get </p>
<blockquote>
<p>Call to undefined method Illuminate\Database\Query\Builder::attach()</p>
</blockquote>
<p>I have updated config/auth.php with</p>
<pre><code>'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
</code></pre>
<p>and name space in each model to App\Models; and also inside composer.json</p>
<pre><code>"autoload": {
"classmap": [
"database",
"app/Models"
],
</code></pre>
<p>and did composer dump-autoload. Why am I getting error for attach() method? Did I forget something?</p>
| <p>Wanted to comment but:
Sorry that this is an answer but can't comment before I have 50 reps':</p>
<p>Can you please provide the User class? Including the uses of other classes/traits.</p>
|
Image loading from url still not fast enough using a background queue <p>I started a background queue to load the image first, and then update the UIImageView's image in the main queue.</p>
<pre><code> int i = 0;
for (UIImageView *imageView in self.featuredPhotoImageViewCollection) {
dispatch_async(dispatch_queue_create("imageQueue", NULL), ^{
NSURL *url = [NSURL URLWithString:[featuredPhotos[i] valueForKey:@"url"]];
UIImage *image = [UIImage animatedImageWithAnimatedGIFURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = image;
});
});
i++;
}
</code></pre>
<p>However, it is still not fast enough. There is 0.5 - 1 sec delay. Any other suggestion other than using a background queue?</p>
| <p>U are misunderstanding the use of background queue. In your code, iOS will start to execute your background code while leaving the main queue not doing anything until it is finished the background code and then update your image view in the main queue. </p>
<p>Therefore, no matter u use what queue in the background, these will not accelerate your speed. </p>
<p>The normal use of it is
1)showing loading indicator,
2)background queue { do something
3)main queue{ hide loading indicator & update UI }}</p>
<p>In your case, my suggestion is to show the snapshot of your GIF images as the indicator as a mentioned above. Or you can simply just show the indicator. </p>
<p>Or preload all the GIF images some where else and just show it here. Loading multiple images always takes some time. </p>
|
Is it good practice to save separate server and ui files in R Shiny? <p>There are at least two different ways of storing and deploying a Shiny app. </p>
<p>The first is to save <code>server.R</code> and a <code>ui.R</code> in <code>dir</code>files and run the app from the directory via <code>runApp(appDir = dir)</code>.</p>
<p>The second is to define both <code>server</code> and <code>ui</code> in a single <code>app.R</code> file and run it from there: </p>
<pre><code>ui <- fluidPage(
actionButton("child","child", icon("child"))
)
server <- function(input, output) {
}
shinyApp(ui = ui, server = server)
</code></pre>
<p>I understand that there are human-level reasons why you might want to have <code>server</code> and <code>ui</code> in different files (eg. if the code is extensive), but most of the Shiny apps I come accross seem to follow the convention of using differente files. I realise that some people might also just be used to this since it was the original procedure. But, does is make any difference, technically?</p>
| <p>According to the tutorial video from RStudio's website (the makers of Shiny), it makes no difference technically.</p>
<p><a href="https://www.rstudio.com/resources/webinars/how-to-start-with-shiny-part-1/" rel="nofollow">https://www.rstudio.com/resources/webinars/how-to-start-with-shiny-part-1/</a></p>
|
Check browser cookie in AngularJS <p>I set cookie by <code>hapi-auth-cookie</code>. Can i check in AngularJS is cookie exists? </p>
<h2>data.js</h2>
<pre><code>server.register(Cookie, function(err) {
if(err) {
console.error(err);
throw err;
}
server.auth.strategy('session', 'cookie', {
password: 'fuckthebritisharmytooralooralooraloo',
isSecure: false,
cookie: 'session',
ttl: 24*60*60*1000
});
server.route({
method: 'POST',
path: '/login',
config: {
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
},
handler: function(req, res) {
if (req.auth.isAuthenticated) {
console.info('Already!');
req.cookieAuth.clear(); // Delete
return res.redirect('/');
}
var username = req.payload.username;
db.get('user_' + req.payload.username).then(function(data) {
var user = data;
var pass = data.password;
if(!user) {
return console.error('Can`t find user!');
}
var password = req.payload.password;
return Bcrypt.compare(password, pass, function(err, isValid) {
if(isValid) {
req.server.log('Boom, okay!');
req.cookieAuth.set(user);
return res.redirect('/');
}
return res.redirect('/login');
})
})
.catch((err) => {
if (err) {
console.error(err);
throw err;
}
});
}
}
});
});
</code></pre>
<p><a href="http://i.stack.imgur.com/9wTM5.png" rel="nofollow"><img src="http://i.stack.imgur.com/9wTM5.png" alt="enter image description here"></a></p>
| <p>You can access like this if you are using <a href="https://docs.angularjs.org/api/ngCookies/service/$cookies" rel="nofollow"><code>Angularjs 1.4</code></a> and above</p>
<pre><code>angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
$scope.session = $cookies.get('session');
}]);
</code></pre>
|
How to create new string in C++ by two other ones? <p>I want to create <code>string</code> <code>"hello1world</code> by this two strings:</p>
<pre><code>string s1 = "hello"
string s2 = "world"
</code></pre>
<p>I do this:</p>
<pre><code>string my_str;
sprintf(my_str, "%s1%s", s1, s2);
</code></pre>
<p>But I have an error:</p>
<pre><code>error: cannot convert âstd::__cxx11::string {aka std::__cxx11::basic_string<char>}â to âchar*â for argument â1â to âint sprintf(char*, const char*, ...)â
sprintf(my_str, "%s1%s", s1, s2);
</code></pre>
<p>How to do it properly?</p>
| <p>Please don't use <code>sprintf</code>. It only supports <code>char[]</code> strings, i.e. C strings. So that's why it doesn't compile when you pass <code>std::string</code>.</p>
<p>With <code>std::string</code>, a simple <code>+</code> is all you need:</p>
<pre><code>string my_str = s1 + s2;
</code></pre>
|
Swift - Firebase function signInWithEmail don't execute in the first call <pre><code>@IBAction func loginEmailButton(sender: AnyObject) {
FIRAuth.auth()?.signInWithEmail(email.text!, password: password.text!, completion: { (user, error) in
if error != nil {
if let errCode = FIRAuthErrorCode(rawValue: error!.code) {
switch errCode {
case .ErrorCodeInvalidEmail:
self.emailLoginStatus = "invalid email"
case .ErrorCodeUserDisabled:
self.emailLoginStatus = "User account disabled"
case .ErrorCodeWrongPassword:
self.emailLoginStatus = "Wrong Password"
case .ErrorCodeUserNotFound:
self.emailLoginStatus = "User not found"
case .ErrorCodeNetworkError:
self.emailLoginStatus = "Could not connect"
default:
self.emailLoginStatus = "Login Error"
}
}
}else{
self.emailLoginStatus = "Logged"
}
})
if self.emailLoginStatus == "Logged"{
self.performSegueWithIdentifier("emailLoginToSearchSegue", sender: self)
}else{
showAlert(emailLoginStatus)
}
}
</code></pre>
<p>I did debug the code step by step and this is the situation: When I tap the <code>loginEmailButton</code> for the first time, the email and password parameters are set to <code>signInWithEmail</code> function, but this function doesn't execute (the next step on debug goes directly out of function without run the completion block).</p>
<p>Then the simulator shows the alert message without text, but if I close the alert and tap the <code>loginEmailButton</code> again, the <code>signInWithEmail</code> is executed correctly and shows the alert with the correct message. I even tried updating the Firebase pods but the problem still remains.</p>
<p>Any suggestion? Thanks!</p>
| <p>Its asynchronous issue. <strong><code>signInWithEmail</code></strong> makes an asynchronous call to the server, meaning this call will be loaded in a different network thread, which takes some time to complete, but since your <code>performSegueWithIdentifier</code> is put outside the completionBlock so it get's executed even before sign In could be completed, But when you press your button next time your users had been previously been signed in from your first call, so it segues... </p>
<p>Just put the </p>
<pre><code>self.performSegueWithIdentifier("emailLoginToSearchSegue", sender: self)
</code></pre>
<p>inside the <code>signInWithEmail</code> completionBlock().</p>
<pre><code>@IBAction func loginEmailButton(sender: AnyObject) {
FIRAuth.auth()?.signInWithEmail(email.text!, password: password.text!, completion: { (user, error) in
if error != nil {
if let errCode = FIRAuthErrorCode(rawValue: error!.code) {
switch errCode {
case .ErrorCodeInvalidEmail:
self.emailLoginStatus = "invalid email"
case .ErrorCodeUserDisabled:
self.emailLoginStatus = "User account disabled"
case .ErrorCodeWrongPassword:
self.emailLoginStatus = "Wrong Password"
case .ErrorCodeUserNotFound:
self.emailLoginStatus = "User not found"
case .ErrorCodeNetworkError:
self.emailLoginStatus = "Could not connect"
default:
self.emailLoginStatus = "Login Error"
}
}
}else{
self.performSegueWithIdentifier("emailLoginToSearchSegue", sender: self)
}
})
}
</code></pre>
|
Accuracy of clock() function in C <p>I have some code that tries to determine the execution time of a code block.</p>
<pre><code>#include <time.h>
#include <stdio.h>
int main()
{
clock_t start_t, end_t, total_t;
int i;
start_t = clock(); //clock start
printf("Starting of the program, start_t = %ld\n", start_t);
printf("Going to scan a big loop, start_t = %ld\n", start_t);
for(i=0; i< 10000000; i++) //trying to determine execution time of this block
{
}
end_t = clock(); //clock stopped
printf("End of the big loop, end_t = %ld\n", end_t);
total_t = (long int)(end_t - start_t);
printf("Total time taken by CPU: %lu\n", total_t );
return(0);
}
</code></pre>
<p>The output of the code snippet on my machine is </p>
<pre><code>Starting of the program, start_t = 8965
Going to scan a big loop, start_t = 8965
End of the big loop, end_t = 27259
Total time taken by CPU: 18294
</code></pre>
<p>So if my CPU was running at 21 MHz and assuming that this was the only thing getting executed, each machine cycle would be approximately equal to 47 nanoseconds so (18294 * 47) = 859818 nanoseconds.</p>
<p>Would this be the execution time for the for loop in my code? Am I making some incorrect assumptions here.</p>
| <p>The unit of time used by the <code>clock</code> function is arbitrary. On most platforms, it is unrelated to the processor speed. It's more commonly related to the frequency of an external timer interrupt â which may be configured in software â or to a historical value that's been kept for compatibility through years of processor evolution. You need to use the macro <code>CLOCKS_PER_SEC</code> to convert to real time.</p>
<pre><code>printf("Total time taken by CPU: %fs\n", (double)total_t / CLOCKS_PER_SEC);
</code></pre>
<p>The C standard library was designed to be implementable on a wide range of hardware, including processors that don't have an internal timer and rely on an external peripheral to tell the time. Many platforms have more precise ways to measure wall clock time than <code>time</code> and more precise ways to measure CPU consumption than <code>clock</code>. For example, on POSIX systems (e.g. Linux and other Unix-like systems), you can use <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/getrusage.html" rel="nofollow"><code>getrusage</code></a>, which has microsecond precision.</p>
<pre><code>struct timeval start, end;
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
start = usage.ru_utime;
â¦
getrusage(RUSAGE_SELF, &usage);
end = usage.ru_utime;
printf("Total time taken by CPU: %fs\n", (double)(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e-6);
</code></pre>
<p>Where available, <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/clock_gettime.html" rel="nofollow"><code>clock_gettime(CLOCK_THREAD_CPUTIME_ID)</code></a> or <code>clock_gettime(CLOCK_PROCESS_CPUTIME_ID)</code> may give better precision. It has nanosecond precision.</p>
<p>Note the difference between precision and accuracy: precision is the unit that the values are reported. Accuracy is how close the reported values are to the real values. Unless you are working on a <a href="https://en.wikipedia.org/wiki/Real-time_computing" rel="nofollow">real-time system</a>, there are no hard guarantees as to how long a piece of code takes, including the invocation of the measurement functions themselves.</p>
<p>Some processors have <em>cycle</em> clocks that count processor cycles rather than wall clock time, but this gets very system-specific.</p>
<p>Whenever making benchmarks, beware that what you are measuring is the execution of this particular executable on this particular CPU in these particular circumstances, and the results may or may not generalize to other situations. For example, the empty loop in your question will be optimized away by most compilers unless you turn optimizations off. Measuring the speed of unoptimized code is usually pointless. Even if you add real work in the loop, beware of toy benchmarks: they often don't have the same performance characteristics as real-world code. On modern high-end CPUs such as found in PC and smartphones, benchmarks of CPU-intensive code is often very sensitive to cache effects and the results can depend on what else is running on the system, on the exact CPU model (due to different cache sizes and layouts), on the address at which the code happens to be loaded, etc.</p>
|
Android: Cast SDK v3 CastOptionsProvider not detected in release build <p>I've correctly declared CastOptiponsProvider manifest.xml</p>
<pre><code> <meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="org.lao.yao.kd.cast.CastOptionsProvider" />
</code></pre>
<p>Anyway I got this error message only when I build app for release:</p>
<pre><code>java.lang.ClassNotFoundException: org.lao.yao.kd.cast.CastOptionsProvider
</code></pre>
<p>Thi is my CastOptionsProvider class:</p>
<pre><code>public class CastOptionsProvider implements OptionsProvider {
@Override
public CastOptions getCastOptions(Context context) {
NotificationOptions notificationOptions = new NotificationOptions.Builder()
.setActions(Arrays.asList(MediaIntentReceiver.ACTION_SKIP_NEXT,
MediaIntentReceiver.ACTION_TOGGLE_PLAYBACK,
MediaIntentReceiver.ACTION_STOP_CASTING), new int[]{1, 2})
.setTargetActivityClassName(ExpandedControlsActivity.class.getName())
.build();
CastMediaOptions mediaOptions = new CastMediaOptions.Builder()
.setImagePicker(new ImagePickerImpl())
.setNotificationOptions(notificationOptions)
.setExpandedControllerActivityClassName(ExpandedControlsActivity.class.getName())
.build();
return new CastOptions.Builder()
.setReceiverApplicationId(MyJsonConfig.getPrefString(MyJsonConfig.KEY_CHROMECAST_RECEIVER_ID, context) )
.setCastMediaOptions(mediaOptions)
.build();
}
@Override
public List<SessionProvider> getAdditionalSessionProviders(Context appContext) {
return null;
}
private static class ImagePickerImpl extends ImagePicker {
@Override
public WebImage onPickImage(MediaMetadata mediaMetadata, int type) {
if ((mediaMetadata == null) || !mediaMetadata.hasImages()) {
return null;
}
List<WebImage> images = mediaMetadata.getImages();
if (images.size() == 1) {
return images.get(0);
} else {
if (type == ImagePicker.IMAGE_TYPE_MEDIA_ROUTE_CONTROLLER_DIALOG_BACKGROUND) {
return images.get(0);
} else {
return images.get(1);
}
}
}
}
</code></pre>
<p>}</p>
<p>I also use proguard for my release build. </p>
| <p>I've run into this issue before with Proguard and external libraries (especially Google's stuff). I used the following in the <code>proguard-rules.pro</code> file:</p>
<pre><code>-keep class org.lao.yao.kd.cast.CastOptionsProvider { *; }
</code></pre>
<p>Also your CastIntentReceiver.</p>
<pre><code>-keep class org.lao.yao.kd.cast.CastIntentReceiver { *; }
</code></pre>
<p>For good measure, I also add these lines:</p>
<pre><code>-keep class android.support.** { *; }
-keep class com.google.** { *; }
-keep class java.nio.file.** { *; }
</code></pre>
|
Angular 2 Chart.js and NG2-Charts Not Binding Data Objects After Updates To Project <p>I have been working on a project in Angular-2 using the starter project found <a href="https://github.com/mrholek/CoreUI-Free-Bootstrap-Admin-Template/tree/master/Angular2_CLI_Full_Project" rel="nofollow">here</a>, </p>
<p>The project worked great till I made some updates to my environment and project. Now the data objects won't bind. It seems like charts.js is not being imported into the project correctly. </p>
<p>I did see in the docs <a href="http://valor-software.com/ng2-charts/" rel="nofollow">Here</a> it states to embed the charts.js file into the html file. This is done in the example by adding node_modules to the src. I was under the impression this was a huge no no! I did try this but can't get the app to expose the file when referenced in that way.</p>
<p>Current versions</p>
<pre><code>angular-cli: 1.0.0-beta.17
node: 6.7.0
os: darwin x64 Sierra
npm: 3.10.3
</code></pre>
<p>After updating to </p>
<pre><code>"angular-cli": "1.0.0-beta.17"
</code></pre>
<p>I started getting errors. I went ahead and updated everything to the latest versions in hope this would clear them. it appears that Charts.js is not being imported to the project after updates. Charts were displaying fine before updating angular-cli. Now that I have updated everything even rolling back won't seem to fix the problem. </p>
<p>Basically anywhere in my component.ts file that I bind a data object to the chart it gives me errors saying that the data object is not a known property off basic-chart. I believe this is a versioning issue and it is not being imported into the project correctly after updates. </p>
<p>I was importing the charts like this in angular-cli.json</p>
<pre><code>"scripts": [
"../node_modules/chart.js/dist/Chart.bundle.min.js",
"../node_modules/chart.js/dist/Chart.min.js"
],
</code></pre>
<p>Then in app.module.ts</p>
<pre><code>import { ChartsModule } from 'ng2-charts/ng2-charts';
@NgModule({
imports: [
BrowserModule,
routing,
Ng2BootstrapModule,
ChartsModule
],
</code></pre>
<p>Current versions I am running, </p>
<pre><code>"dependencies": {
"@angular/common": "2.0.2",
"@angular/compiler": "2.0.2",
"@angular/core": "2.0.2",
"@angular/forms": "2.0.2",
"@angular/http": "2.0.2",
"@angular/platform-browser": "2.0.2",
"@angular/platform-browser-dynamic": "2.0.2",
"@angular/router": "3.0.2",
"@angular/upgrade": "2.0.2",
"core-js": "^2.4.0",
"rxjs": "5.0.0-beta.12",
"ts-helpers": "^1.1.1",
"zone.js": "0.6.25",
"chart.js": "^2.3.0",
"ng2-bootstrap": "^1.1.5",
"ng2-charts": "^1.3.0",
"moment": "^2.15.1"
},
"devDependencies": {
"@types/jasmine": "^2.2.34",
"angular-cli": "1.0.0-beta.17",
"codelyzer": "1.0.0-beta.0",
"jasmine-core": "^2.5.1",
"jasmine-spec-reporter": "2.7.0",
"karma": "1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "4.0.9",
"ts-node": "1.4.1",
"tslint": "^3.15.1",
"typescript": "^2.0.3"
}
</code></pre>
<p>Here are a few of the errors,</p>
<pre><code>Can't bind to 'datasets' since it isn't a known property of 'base-chart'.
1. If 'base-chart' is an Angular component and it has 'datasets' input, then verify that it is part of this module.
2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("iv>
<div class="chart-wrapper p-x-1">
<base-chart class="chart" [ERROR ->][datasets]="lineChart1Data" [labels]="lineChart1Labels" [options]="lineChart1Options" [colors]="lineC"): DashboardComponent@19:46
Can't bind to 'labels' since it isn't a known property of 'base-chart'.
1. If 'base-chart' is an Angular component and it has 'labels' input, then verify that it is part of this module.
2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("ss="chart-wrapper p-x-1">
<base-chart class="chart" [datasets]="lineChart1Data" [ERROR ->][labels]="lineChart1Labels" [options]="lineChart1Options" [colors]="lineChart1Colours" [legend]="line"): DashboardComponent@19:74
Can't bind to 'options' since it isn't a known property of 'base-chart'.
1. If 'base-chart' is an Angular component and it has 'options' input, then verify that it is part of this module.
2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
(" <base-chart class="chart" [datasets]="lineChart1Data" [labels]="lineChart1Labels" [ERROR ->][options]="lineChart1Options" [colors]="lineChart1Colours" [legend]="lineChart1Legend" [chartType]="l"): DashboardComponent@19:102
Can't bind to 'colors' since it isn't a known property of 'base-chart'.
1. If 'base-chart' is an Angular component and it has 'colors' input, then verify that it is part of this module.
2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("class="chart" [datasets]="lineChart1Data" [labels]="lineChart1Labels" [options]="lineChart1Options" [ERROR ->][colors]="lineChart1Colours" [legend]="lineChart1Legend" [chartType]="lineChart1Type" (chartHover)="c"): DashboardComponent@19:132
Can't bind to 'legend' since it isn't a known property of 'base-chart'.
1. If 'base-chart' is an Angular component and it has 'legend' input, then verify that it is part of this module.
2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("eChart1Data" [labels]="lineChart1Labels" [options]="lineChart1Options" [colors]="lineChart1Colours" [ERROR ->][legend]="lineChart1Legend" [chartType]="lineChart1Type" (chartHover)="chartHovered($event)" (chartCl"): DashboardComponent@19:161
Can't bind to 'chartType' since it isn't a known property of 'base-chart'.
1. If 'base-chart' is an Angular component and it has 'chartType' input, then verify that it is part of this module.
2. If 'base-chart' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("hart1Labels" [options]="lineChart1Options" [colors]="lineChart1Colours" [legend]="lineChart1Legend" [ERROR ->][chartType]="lineChart1Type" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)"
"): DashboardComponent@19:189
</code></pre>
| <p>There is no longer the selector <code>base-chart</code> valid.</p>
<p>Per ng2-charts <a href="https://github.com/valor-software/ng2-charts/blob/development/CHANGELOG.md#breaking-changes" rel="nofollow">changelog</a></p>
<blockquote>
<p>base-chart component became baseChart directive so you need to convert</p>
</blockquote>
<pre><code><base-chart...></base-chart>
</code></pre>
<p>to</p>
<pre><code><canvas baseChart...></canvas>
</code></pre>
<p>and most probably wrap in </p>
<pre><code><div style='display:block'>...</div>
</code></pre>
<p>See <strong><a href="https://plnkr.co/edit/edlnC7yLjpSmLF1RFjVB?p=preview" rel="nofollow">Plunker Example</a></strong></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.