text
stringlengths 1
1.04M
| language
stringclasses 25
values |
|---|---|
<reponame>impastasyndrome/Lambda-Resource-Static-Assets<gh_stars>0
function numRegions(graph) {
let visited = new Set();
// regions count
let regions = 0;
// iterate through nodes in the graph
for (let node in graph) {
if (visited.has(node)) continue;
// skip iteration if set has node otherwise call upon the function and increase the count a
depthFirst(graph, node, visited);
regions++;
}
return regions;
}
function depthFirst(graph, node, visited) {
if (visited.has(node)) return;
visited.add(node);
// iterate through the neighbors and visit using the depthfirst function
graph[node].forEach((neighbor) => {
depthFirst(graph, neighbor, visited);
// return true;
});
}
module.exports = {
numRegions
};
|
javascript
|
383 Private Members' Resolution
unemployed like doctors and engineers, etc. Arts graduates who are unemployed, are still asking for employment. They are qualified persons who are doing menial jobs incompatible to their education also. The foremost task before the nation is to give employment opportunity to a large number of unemployed people.
We may take a lesson from Tamil Nadu model. In Tamil Nadu, the State Chief Minister and our leader, Dr. Kalaignar has announced a new employment scheme, that is, appointing large scale youngsters under 'people welfare worker' scheme. What is their work? Their main job is to promote self employment amongst the rural population. They are going to appoint 25000 women for propagation of prohibition. This recruitment is only to provide employment opportunities to unemployed youngsters and women.
Like that, in Central Government also, rural unemployment can be erased only by bringing more dry lands under cultivation. Cultivation is possible only when there is irrigation. Irrigation is possible only when national rivers are connected with each other. At least, if southern rivers are connected with each other, it will help the cultivation of the dry lands.
I want to mention another important thing, that is, our hon. Minister of Industry is bringing in a lot of industries and helping to start new industries with heavy investments.
This will fulfil the employment opportunities to a certain extent. Every industry is having its own by-products. There are many chances for the growth of the small scale industries using out of the by-product. If an industry having a by-product is established in an area, the students and the youngsters should be educated in such a way that they themselves get employed in small scale industries which are being run out of the by-products. Putting science and technology exhibition in every District headquarters also will help for the promotion of the small scale industries. Educating the youngsters only will help to solve the unemployment problem.
With these few words, I conclude my speech.
SHRI RAMASHRAYA PRASAD SINGH (Jahanabad) : Sir, I fully support the Bill introduced by Shri Katheria, because Small Scale Industries Sector is like an industry providing employment in an Agriculture based country. Small Scale industries existed in our country right from the way beginning. You may be
Private Members' Resolution 384
aware that when it was undivided India, partition had not taken place Dhaka Muslin used to be produced here. Those who used to work in small industries say that large quantity of this cloth used to be exported from here. A lot of foreign exchange was earned therefrom and lot of people were provided with employment, but today rural industries have been destroyed by big industries. They have no market of their own as a result of which they are almost finished today. Today a large number of people in India make handloom cloth. Those people are today leaving that profession. We should see what is their condition today.
Small Industries Sector is getting very weak in our country which is aggravating unemployment in our country. With the increase in unemployment the unemployed youth in the country is getting out of national mainstreams. They are going toward wrong paths. Country is spending a lot of money to save them from going towards wrong path. You may glance towards any direction, what is this Bodo movement. I come from Jahanabad. The area has a large number of poor unemployed youth; they do not have any jobs. Earlier they were running small industries which have now been destroyed. Black-smith who used to work here, were making agricultural implements. Implements made by them were used in Agricultural operations. I am not against big Industries but implements which were produced by small industries are todays being produced by Tata and Birla. Small hoe (Kudali) was made by them and now is being made by Tata-Birla also. But the quality of the both is different. Both perform same functions but appearance is different. People adopt beautiful appearing things which are produced by big companies and goods produced by blacksmith are not sold. They have left their professions. Those who were earlier making hoes are now making guns which are being sold to terrorists. It is creating problem for the country.
I want that Government should pay attention towards small industries. Economic liberalisation has brought Multinational Companies to our country. These companies would sell even packed good. Small hotels which are in business today will be closed because packed food would be comparatively cheaper. In that case people will prefer cheaper food. I want to point out this thing to you.
Hon. Minister for Industries is present here. He should consider over this that what is the condition of Small Industries today. If small industries have to the remained today then first of all we have to put our resources to proper use. We are not short of resources. Whatever resources we possess could help us. You can see what is happening. Those who work do not proeper
385 Private Members' Resolution
but plunders prosper. We feel that ours is a poor country. A number of people said that so long Lok Sabha is there people will come and make statements. But simply making statements is not enough. Great intellectuals and economists are also sitting here but nothing is being done. We have to tackle corruption first before we utilize properly our meagre resources. Unless corruption is finished from the country small industries may not be able to develop despite whatever amount you may spend on their development and unemployment problem may not be solved. The country. may continue to run in this manner.
With these words I stop my speech.
SHRI P.C. CHACKO (Mukundapuram) : Mr. Chairman, Sir, I am grateful to you for this opportunity. Sir, continuously, on the successive third occasion, this House is discussing a very vital topic regarding the promotion and encouragement to be given to the small scale industries.
Sir, before I say a few words about the most important topic before us. I would like to congratulate Shri Prabhu Dayal Katheria who was brought this Resolution. Very rarely such resolutions come before the House where a procedural formalities even though we will agree with the essence of the Resolution, we always advise them to withdraw the Resolution after taking into account the necessity or agreeing with the essence of the Resolution. But here we can depart from the past, probably if the hon. Minister of Industry agrees and the House can unanimously adopt this Resolution. I find no reason why we should not do so because the importance of the small scale industries as being highlighted through this Resolution in a befitting manner.
Today we are living in an age of modernisation liberalisation, globalisation and all such things. All these things are very much essential to the development of our economy and we are all struggling hard to take our economy and integrate it with the world economy.
The Indian situation is such that if we are isolated from the world economy, we cannot grow beyond a level having assessed our role for the last almost 50 years now, we have come to the conclusion that we have to integrate our economy with the world economy. In that situation the relevance of the small scale industry should not be lost sight of.
I am very happy that we have today a Minister of industry who can understand the significance of this Resolution and the topic which we are discussing because, most often, when we are too much involved
Private Members' Resolution 386
in the industrial development aspect, which is mainly pertaining to the large industries and the foreign direct investment and various other things, always the small things are lost sight of. That happens everywhere. The small scale industry in India today is struggling as never before because of certain problems which are plugging this sector. If we do not attend to this sector with immediate effect, then probably one of the most flourishing sectors of our economy may be crippled further. Today our statistics say and I will also vouchsafe that a major portion of India's industrial export is not coming from the major industry, but it is coming from the small scale industry. That is the point where we can understand the importance of this industry and also the employment potential generated by it. Large scale industries are coming; foreign direct investments are coming, but the modern industries which are investing Rs. 500 crore or Rs. 1,000 crore, they are all automatic or computer controlled, etc. and the employment potential from them is very little.
I know an example. In my constituency where an investment of Rs. 600 crore was made, the employment is provided to only 50 persons. So, this happens to be the modern industry. Probably, there is no way out of it. So, the employment potential in a country like India where educated unemployment is the biggest curse to the society, is maximum available in the country and that is the most important factor.
My friend, Shri Prithviraj D. Chavan has highlighted a point and I am sure the the hon. Minister of Industry has taken note of that. So, we have to think seriously of changing the definition of small scale industry. Now, it is being defined on the basis of the capital investment.
In a recent reply made in this House, the hon. Minister of Industry has said that no step has been taken for increasing the limit of the small scale industry from the existing limit of Rs. 75 lakh to Rs. 3 crore. There may be some procedural wrangles and it might not have come to the notice of the hon. Minister. In the very same House the Government, whether is the United Front Government or a Congress Government Government is a continuing mechanism
in the Tenth Lok Sabha, I remember, the then Minister of Industry said that the limit of the small scale industry is being revised from Rs. 75 lakh to Rs. 3 crore. As far as the capital investment is concerned, the limit is Rs. 75 lakh and this limit was decided some 20 years back. However, because of escalation of cost and so many other factors, this amount of Rs. 75 lakh cannot be now today decided as the limit for a small scale industry. So, it should be raised to a minimum of Rs. 3 crore. That suggestion is already being discused and debated in various fora and, I am sure that
387 Private Members' Resolution
the Minister of Industry is very well aware of that and a formal decision in this matter is very much essential because it has been a long pending issue before the industrialisation problems of our country.So, I am sure that the hon. Minister of Industry will lose no time to take an early decision that at least Rs.3 crore is decided as the minimum limit for the small scale industry.
As my friend, Shri Prithviraj D. Chavan has said, we should club the employment potential also when we decide the definition of the small scale industry. That point is amply made clear by him. So, I am not going to repeat it again. But I come from a State where educated unemployment is the maximum in the country; where the registered Employment Exchange rolls are running into lakhs and million. So, whichever industry which provides more employment opportunities should be given more incentives. Now a package of iincentive is being introduced by various State Governments and, I think almost all the State Governments are giving various package of incentives. Now, people are losing interest because of the subsequent development after the New Economic Policy. There is a tendency to ignore this sector. That should not happen because in our industrial economy, the importance of this sector is not going to decrease and it is only going to increase.
With that view in mind, if the Government of India can codify this and make some kind of uniform arrangement as far as this package of incentives is concerned, that will go a long way to help the small scale indutries. Some items of the package of assistance being extended to various industries are tax holidays, tax exemptions and investment allowances. We have been listening for a long time about the entrepreneurial training, raw material assistance, raw material banks, single window clearance. But as the hon. Minister of Industry knows, the single window system is not functioning anywhere in this country though we have been hearing this for the last 25 years that various State Governments are saying that it is all single window clearance.
Sir, anyone who passes out of a polytechnic or an engineering college as a technically qualified and competent person and thinks of starting his own industry, he will be landing in trouble. That kind of situation is there. From the very registration, procedures start the agony of the entrepreneur. If he goes to register an industry, it needs 101 clearances from environmental angle, from panchayats, from municipalities and from various other agencies. Once you get it registered, even to get a telephone connection, to get a water connection or to get an electricity connection,
Private Members' Resolution 388
it takes an unreasonably long period of time. So, what you are investing is keeping in view the gestation period. When your gestation period is extended for such reasons which are beyond your control, what will happen to you?
It is said that the money is the costliest in this country today. In no bank, money is available at an interest less than 16 per cent. A bank says that they are giving money at interest of 16 per cent. What does it mean? It means that it is 16 per cent plus various other charges. All these things put together will finally make the 16 per cent as 18 per cent. No small scale industry with so much money can reach the break-even level. No industry can have that kind of a margin. We cannot think of any industry or any business which is generating more than 18 or 20 per cent profit. So, the entire profit that you are making is going to be eaten up by this interest regime. So, Sir, there has to be a subsidy scheme by the Government of India for subidising the interest rate. I am not saying that the Government of India has not introduced a system of investment subsidy. The problem with the investment subsidy is that if the requirement is of Rs. 100 crore, your provision may be for Rs. 10 crore and hardly 10 per cent of the applicants may be getting your in vestment subsidy. This is happening in various State Governments. They are announcing schemes but the provision made is very small. Even as far as the Government of India is concerned, the requirement is X and what is provided for, including various incentives, tax benefits and all these things put together, is Y which is comparatively a very small figure. This happens.
So, Sir, probably the institutional finance which is available in the country, a separate banking institution, SIDBI is formed for small scale industries' financing. But from no bank, from no Industrial Development Corporation in the whole country, you can get money at an interest less than 15 or 16 per cent. What are these banking institutions doing? They will simply reach their targets by some cooked up information. If you ask for a report whether they have reached the priority sector the priority sector includes various other things also they will somehow reach their targets and the real small scale industry is always finding it extremely difficult to get finance from industrial financing institutions.
Probably, there is one area of interest subsidy which can help small scale industries. Suppose a subsidy of two or three per cent is given for industrial loans, that will go a long way. At the same time, the Government of India's commitment will not be too much. Since we cannot finance the entire capital or the working capital requirement, even the interest subsidy scheme effectively implemented throughout the country will go a long
389 Private Members' Resolution
way in helping the small scale industries.
At the same time, Sir, we have been giving some kind of protection to our small scale industries for the last so many years. Unfortunately today, because of the new situation which is being developing in this country, this protection is going down. There are many items reserved for the small scale industries, but the encroachment is continuously being done where the large-scale industries under some pretext or the other are encroaching into the reserved area of the small scale industries.
If that is happening what action have you taken? I have not come across a single instance where the Government has taken action against the medium and farge scale industry which is producing the products reserved for the small scale industries. That is happening. They are reaping this benefit. So. certain areas which are reserved for the small scale industry should strictly be adhered to and they should get all the benefits.
Another thing is that there are raw material and marketing problems. We have been giving some kind of marketing support and advertising support. We are living in a very competitive environment today. It is not the sellers market. It is always buyers' market. So the small scale industry has to compete with the medium and large scale industry. Today, after the opening up of the economy, the multinationals are also coming and they are also to an extent competing with the small scale industry. So, the Government should enable our small scale industries to stand on their own legs. Protectionism should continue. I am not arguing that the market forces should not decide and unhealthy protection should be there. I am not arguing that because, this old system is also giving rise to a lot of corruption and other things. At the same time, if strictly decided which are the products reserved for the small scale industry and which are the incentives available to the small scale industry under no circumstances such benefit should be taken advantage of by the medium and large scale industry.
Sir, we have a responsibility towards small scale industry. An entrepreneur starting his own factory has to take 101 clearances right from registration to the production stage. He has to run from pillar to post. Nobody is there to help him. If something has to be completed in 20 months and it is going to be extended to 30 months, then what happens is that the whole thing becomes unviable. It becomes a still born child.
In most of the States, electricity is a big problem. After completing everything and after installing the machinery and other things, you cannot get electricity connection. This is happening. What is the priority? You
Private Members' Resolution 390
go to any State Electricity Board, this is the position. We may say so many things that all kinds of priorities are there, but I can tell you from my experience that in the State from where I am coming, there is absolutely no incentive from the Electricity Boards for the small scale industry. In fact, it is a disincentive. So, after you set up your industry and you are ready to go to stream, at that time electricity is not available. These kinds of bottlenecks and hurdles are to be overcome on a day-to-day basis by the entrepreneurs. But that entrepreneur is being penalised by all kinds of Governmental agencies. So, from the single window clearance system up to the marketing support whatever can be offered or whatever can be given by the Government should be given to the small scale industry. The Minister of Industry may kindly consider what are the benefits available, what are the loopholes, how they can be plugged and how the industry can be effectively helped. This kind of codification of the facilities and strict monitoring of the facilities available to the small scale industry is necessary. Whenever we think of small scale industry we cannot think of a situation where small scale industries' opportunities are not being taken away by other medium and large scale industries. If these two-three things are taken care of then comes the craftsman or the traditional industry.
In our country we are not having only large and medium scale industries but we have traditional industries also. The traditional industries are one area where largest number of people are given employment whether it is jute or coir or cashew. All these traditional industries are also essentially small scale industries. At the same time, they have the maximum employment potential. These traditional industries are facing crisis situation today. Sir, we are not giving any kind of support to them. Whatever support was available from the State Government or from the Central Government is gradually being vanished. You take any industry in any State, it is struggling hard to survive. That kind of a situation is there. So in the historic perspective of the country and the historic background of India, the industrial development did really start with the traditional industry. Then it came to small scale industry and then to medium and large scale industries. So, we should not allow this traditional and small scale industry sector to be choked to death. That kind of a situation is prevailing. So, I request the Government that a definite policy for protecting small scale industry is necessary.
Now, after the presentation of the new Budget, the small scale industries are facing some new problems.
Whenever you are altering the tax pattern, whether import duty or excise duty, you should be very careful that it should not affect the small scale industries. I am
391 Private Members' Resolution
sure that the hon. Minister is aware that from the non-traditional raw materials, the small scale paper manufacturers were having a particular slab of excise duty. But now the large units and the small units are treated in the same fashion after the new Budget has come. What is happening? Big industry, with all their infrastructure and paraphernalia, is competing with the small scale units. This is happening. The problem which the medium and small scale paper industry are facing today is a typical example. I have only to point out one example. So, the excise duty, customs duty or import duty, all these duty structures, are being changed. We should be very careful that it is always to the advantage of the small scale industry. Wherever and whenever it has affected the prospects of the small scale industry, it is the duty of the Minister of Industry kindly to see that these hardships are avoided.
The Budget will be finally passed. Maybe the reply is coming on Monday. There are a number of items which we have brought to the notice of the Minister of Finance. We want the support of the Minister of Industry because it is primarily his duty to see that wherever the change in the tax structure is effected in the small scale industry, that should be altered and amended in such a way that they are given some kind of protection. So the traditional industry and the small scale sector which are employing the maximum number of people in the country and which are contributing to the largest portion of our industrial export, these two sectors should be given the top priority. Under no circumstances, the protection hitherto available to this sector should be taken away because of the new environment of the new economic situation. A careful consideration should be given to this sector. That is my only request to the hon. Minister.
Once again, I congratulate Shri Prabhu Dayal Katheria for this commendable Resolution and everybody in this House will agree that this Resolution should be passed and implemented with all sincerity.
SHRI GULAM MOHD. MIR MAGANI (Srinagar) : Sir, so far as industries are concerned unemployment has increased in Jammu and Kashmir on account of closure of factories due to terrorism. A large number of youth are unemployed. I would request the Government as well Minister of Industries the factories which were earlier working in Jammu & Kashmir should be . re-opened so that unemployed can be checked.
So far as Banks are concerned the youth have to face a lot of difficulties in obtaining loans which are given to unemployed youth. They are required to wait for a year. I request the Hon. Minister that procedure
Private Members' Resolution 392
in this regard may be stream lined and the unemployed youth maybe given loans and employment may be provided to them.
So as H.M.T. Watch Factory is concerned, which earlier provided jobs to thousands of people, is presently lying closed. Peace is slowly and slowly returning to Jammu & Kashmir. Democracy is being restored. Parliamentary elections have proved that the situation is improving there by and by. Because of this improvement Assembly Elections are also scheduled to be held there shortly.
Tourism used to provide employment to lot of people in Jammu & Kashmir, but today this activity has virtually come to end. I request the Government to revive this activity. People have become unemployed due to terrorism continuously for 7 years. I request the Government that full attention should be paid towards this and situation improved. With this I support the Resolution.
SHRI SUDHIR GIRI (Contai): Mr. Chairman, Sir, I rise to support the Resolution. The objectives of the Resolution have ben described. The obejctive of, this Resolution is to develop the small scale industries. And for the development of small scale industries, the Mover of the Resolution has put forth some reasons. The reasons given are that for the purpose of eradicating unemployment and creating employment generation, the small scale industries are required to be developed. He has suggested about some means. These means are that the Central Government should make available financial assistance to the small scale industries. He has also suggested that large investment must be made in the infrastructure sector. He has also suggested that the production made in the small scale sector should be reserved for the small scale sector only and the large or medium scale sector should not intervene in this.
And, for this purpose, he has also suggested the setting up of National Craftsmen Development Bank which will create facilities for the small scale sector industries.
Sir, I feel that the small scale industries have a great importance in the Indian economy, not only for the purpose of creating employment or for the purpose of checking the unemployment problem, it is also needed for other wider reasons. It is needed for the purpose that these sectors account for 40 per cent production of the total manufacturing industry. It is the sector of the industry. Forty per cent of the total exports are done by the small scale sector industries. During
393 Private Members' Resolution
1994-95, the export was to the tune of Rs. 26,000 crore and the objective and target fixed for 1995-96 amounted to Rs. 30,000 crore. So, in the field of Indian economy, its role cannot be denied by anybody. Not only this, massive people's participation can be ensured in the small scale industries whereas in other industries such massive scale participation of the people cannot be possible due to which targets also cannot be achieved there.
Not only this, there are some other very important roles which the small scale industries have to play. The development of consciousness as regards nature, removal of superstition, eagerness for learning scientific words, spirit of cooperation, aspiration for better standard of living and ambition for achieving individual freedom all these qualities can be achieved by the people who are moving forward for the small scale industries development. And for this, participation of the masses, participation of the people in this sector is really the most important.
So, Sir, I think the importance of the small scale industries in the perspective of the Indian economy is very much essential, in the sense that it is acceptable to all. In a word, I may say that the human development problems can be solved to some extent through the development of small scale industries and the people can also get the first-hand knowledge of technologies which have been invented throughout the world.
But there are some problems. The main problem is due to inadequate flow of institutional credit. This has been narrated by all the speakers, I think. The financial institutions are very much miser. They do not take into consideration the application or the prayers of the small scale industry producers. So, the Government must ensure the adequate flow of credit to the small scale industries by financial institutions. We should see that the financial institutions are compelled to provide credit facilities to the small scale sector.
Secondly, there is a problem of non-availability of quality raw-material. This is a major factor. Generally, varieties of designs can be found in the small scale sector but the quality raw materials are not available in the market. And, the people, the artists who can develop different varieties of designs, are found to be in the grip of the greedy businessmen, who can purchase their designs.
The third issue is that infrastructure is not provided and that is why the small scale industries do not get proper advertisement. They are not given adequate opportunities to get themselves known to the people of different communities. In some cases it has been found that the small scale industries cannot keep pace with
Private Members' Resolution 394
the inventions that are taking place in the modern world. So, these problems have to be circumvented. The Government, for the purpose of solving these problems, have evolved some policy initiatives to help the small scale industries in overcoming these difficulties.
The Government had appointed the Nayak Committee and that Nayak Committee had reported that the RBI should make available adequate and timely flow of credit to the small scale industries. Still, improvement of the credit flow is necessary for setting up of industrial infrastructure development centres. The Government is helping them with only Rs. 2 crore. This amount should be increased. In the perspective of the increasing prices and inflationary pressures, the small scale industries should be given more funds so that they can create their own resources for developing their industries.
I would like to bring to the notice of the Government that recently the big industrial houses in the Indian industry are poking their nose in the matters related to the small scale industries. Even multinational corporations are being permitted to come to the backward areas and see if they can create credit flow and make it available for small scale industries. As a result of this, stiff competition would be there. The small producers would not be in a position to face the stiff competition. I would, therefore, urge upon the Government to nsider all the aspects an not be pressurized by IMF and the World Bank advisers and not follow: diktats. Our Government should follow the principle of self-reliance. Self-reliance would definitely create conditions which would be congenial for development of small scale industries.
I hope that the Government would pursue the matter in the light of the CMP, which has been adopted by them.
SHRI NAND KUMAR SAI (Raigarh) : Sir, thank you very much for providing me an opportunity to speak. In fact small industries can play a vital role in balancing the overall economy in our country. Unfortunately these years we have not paid any attention towards this. 5.6 per cent growth has been reported in it during 1992-93. 7.1 per cent growth is reported to have taken place during 1993-94, but when we look towards the ground realities it appears to me that medium industries are turning into small industries. With the arrival of Multinational Companies in the country the medium industries are turning into small industries. This percentage includes from industries as well.
If we have to keep balance in the economy of the
395 Private Members' Resolution
country we have to give due importance to small and cottage industries in all respects. Hon. Minister has given a number of suggestions here. If small industries are not set up along with big industries people would not get jobs and if they do not have jobs they will not have money in their hands and if they do not possess money they may not be able to purchase goods produced by big industries. Hence you have to maintain economic balance. And if it has to be maintained you have to give encouragement to small industries. Hon. Member of Parliament, Shri Ramashray Prasad Singh is not present here. He was talking about Dhaka Muslin. In earlier times Dhaka Muslin was produced in our country in small industries. A bundle of Dhaka Muslin could be put in a Matchbox. When Britishers came over to our country they had to sell here cloth produced in Lancashire and Birmingham Mills. They therefore cut off the hands of artisans who used to produce Muslin so that they were not able to produce Dhaka Muslin and the industry could be destroyed once for all. Many a similar industries existed in our country.
You go to Kutab Minar in Delhi you will see that the Iron Pillar standing there has not been affected by rust. Who were the artisans who made it. The hon. Minister should look into this. We have recently read in newspaper that Sugarcane growers had to burn their produce because you are neither paying them full amount nor are you allowing him to put his produce to alternative uses. I come from Raigarh. Tomato cultivation is done there. I want to tell you that during the season 700 to 1000 trucks load of tomatoes come there in the market. Tomato growers are not able to market their produce. Here in urban areas tomato is sold at Rs. 20-30 per kilo, but there is nobody to lift the same free.
Residents of 20 villages in Ludeg District in Madhya Pradesh were provided training. I want to say that they may be provided small machines for setting up of village industries and small industries may be set up there so that all of them could get work. Small industries may be set up to make tomato ketchup from tomatoes. to make sauce and arrangements may be made to fill the same in bottles in these small industries. The Government should make arrangements for the marketing of the same. The earlier Government in the State had made a beginning in this regard but after the coming into power of the present Government the efforts came to naught. There are thousands of such things in the country which could provide employment to crores of people. The Government could provide them money, but it does not pay any attention towards this.
Sir, today the urge to become rich has given birth to materialism in the modern world. This tendency is
Private Members' Resolution 396
taking the whole world to which directions. Nobody wants to do hard work today. Harshad Mehta became billionaire overnight. Similarly everybody is running after money. Nobody wants to do labour. Pandit Deen Dayal used to say that we have to establish dignity of labour in the whole country. Whether somebody is rich or poor, whether he is a capitalist or a labourer everybody should know dignity of labour.
These views of Pandit ji are more relevant today. but nobody pays any attention towards these things. This is the reason that if big industries are set up all types of cooperation is extended but small industries are neglected. These industries are not extended co-operation when they start operations. The Resolution moved by Shri Katheria is worth welcome and I support it.
I would like to point out its ill-effects. Big Industries are situated in Towns whereas raw material is available in rural areas. Urban people are earning crores of rupees out of those industries whereas the people living in the areas where raw material is produced are leading poor life. I want to cite an example in this regard. Jal Seed is produced at a number of places in the country but solvent plants to use these seeds are set up in big cities like Bombay. Calcutta, etc. The areas where these seeds are produced and the people who collect the seeds do not get remunerative prices. Today those people are merely getting Rs. 1.50. People have become rich by setting up Solvent Plants. Hence the plants should be set up in concerned areas, where relevant raw materials are produced. Agriculture and mineral based small industries should be set up all over the country only then the economy of the country which has gone out of rails could be brought back on rails. The whole imbalance in the society in which there are Millionairs and billionairs on the one side and large number of those people who have to survive merely on 5-10 rupees. We have to ponder over it seriously and take effective steps to properly implement it.
Sir, there was a time when the village was a selfreliant unit, farmers used to produce grains and other artisans such as blacksmiths, cobblers, washermen, carpenters used to do their respective jobs. But today these industries have vanished and big industries have taken their place. We did not encourage those artisans. They became jobless. Those who were weaving cloth on small looms those looms are not being put to use these days. They were needed and clothes produced by them were exported. Silk and Kosa cloth produced in villages was in great demand. Even today these cloths are in demand. These have their own market in world market. We can earn a lot of foreign exchange through export of carpets. If rural economy is linked with
397 Private Members' Resolution
modern new techniques this country can easily stand on its feet. Economic revolution, employment oriented revolution could take place and nobody will starve of hundgar.
Even the Budget is imbalanced. On the one side is a rich man and on the other there is a poor man. The disparity between the two should be removed and budget improved accordingly. There is a need to adopt correct approach in this regard. There is a difference today between the face of a poor and a rich man, difference between the cloths they wear only because of this economic imbalance :"Ek taraf Samridhi thirakti,
ek aur hai Kangali,
Ek deh per ek na chithara,
ek swarn ke gatno vali"
This is the condition of our country today.
MR. CHAIRMAN Now, we had extended the time for this Resolution by one hour. That is also over. There are five more Members to speak. So, is it the pleasure of the House to extend the time for another one hour?
SHRI PRITIVIRAJ CHAVAN But. Sir, you must allow the next Resolution also to come up.
MR. CHAIRMAN We will extend the time by one hour in which all the five Members can speak for five minutes each and then the hon. Minister will give his reply. The next mover is ready in the House waiting to move his Resolution. I think we must give him an opportunity.
The next speaker may kindly confine only to points for five minutes so that we can finish this Resolution today. So, the time is extended by one more hour.
SHRI NAND KUMAR SAI: Sir, if the Government has made some efforts to set up small industries or tried to help people to stand on their feet hindrences were created. Finance Development Corporation has been set up to help Tribal unemployed youth in Madhya Pradesh. If any youth tries to acquire a vehicle he is provided assistance. I have seen they are given assistance to purchase Mazda and Swaraj Vehicles whose spare parts are not available in villages and small towns. These are foreign vehicles. I wrote to Director that those people are not much benefitted that they are forced to buy foreign vehicles with the financial assistance provided
Private Members' Resolution 398
by the Central Government. I told him to help them in purchasing Tata vehicles whose spare parts are easily available everywhere.
Sir, number of Jhompries is increasing in cities. There are no jobs available in villages and resources are available in rural areas and being utilized in urban areas, with the result that new problems are cropping up in urban areas. Sir, as I do not have much time I would request the Minister to set up small industries in villages. Small industries may be directed towards villages and new economic order may be created in the country by setting up a number of cottage industries in the whole country. Mr. Chairman. Sir, through you I would like to say
“Chalo jahan nirjan kanan mein van kusum muskate hein,
malyaril bhoolata bhoolkar jahan nahin ali jaate hein,
kitne deep bujhe jhari jhurmat mein jyoti pasaar.
chale shunya mein surbhi chhorkar, kitne kusum kumar"
Sir, I want to request the hon. Minister through you let us move towards villages. With these words ! support this Resolution moved by Shri Prabhu Katheria
SHRI K. PARASURAMAN (Chengalpatu) : Sir, I rise to speak on the Resolution moved by Shri Prabhu Dayal Katheria on the problem of unemployment and how to check the growing unemployment situation in the country. I am happy to say that this is my maiden speech and I take part in this subject which is already discussed elaborately by the leaders of this august House.
Sir, in this connection. I would like to point out that in a country like ours, unemployment among the youth has become a perennial problem and the Central and State Governments in the country have been taking concerted efforts on a warfooting to solve the problem. But we find that the problem could not be solved fully. On the other hand the number of unemployed youth has been swelling year after year.
MR. CHAIRMAN: You are not expected to read out. You can refer to the points and speak.
SHRI PRITHVIRAJ D. CHAVAN Sir, he may be excused as this is his maiden speech. He may kindly be allowed to proceed.
SHRI K. PARASURAMAN: Over the last 50 years
399 Private Members' Resolution
of Independence, though growth has taken place in several sectors of economy and per capita income has increased, the increasing number of unemployed persons, particularly educated unemployed youth could hardly be arrested.
Sir, my friend Shri Katheria has urged upon the Government for the provision of financial assistance to the existing small scale industries. In this connection. I would like to remind the Government that it should consider the provision of financial assistance to those small scale industries which produce goods for large scale consumption by the weaker sections within the country and also for goods produced for export purposes for earning foreign exchange.
Sir, the transportation of goods produced in the remote corners of the country has been very difficult and, therefore, the small scale units could not market their goods and ultimately become sick. Government should give over-riding priorities for the provision of Infrastructural facilities like land, road, electricity, marketing of goods produced in small scale units, cheap transportation facilities, bank loans at a very normal rate of interest and advertising of goods produced in the small scale units through television and radio. In States like Tamil Nadu, long coastal areas and forest areas should be reserved only for establishment of small scale industries. The craftsmen, the artisans, educated selfemployed youths, ITI and polytechnic certificate holders should be given sufficient loans by a Development Bank separately set up for this purpose.
Sir, coming to my State of Tamil Nadu, in Government offices like ICF, Railways, Ports, Telecommunications, Postal Department, Atomic Energy Organisation, Kalpakkam, in DAE, CORPS ICCAR, PRP, WIP, CWMF, GSD, KARP, MAPS, PROTECTS, etc., thousands of vacancies are lying vacant in various categories. I would like to plead with the Central Government to take immediate action to fill up these vacancies so that unemployed youths in the State may get employment.
(MR. DEPUTY SPEAKER in the Chair)
Sir, in Kalpakkam, in case of the these projects, the Government had promised that the sons of the soil would be given employment after the establishment of the above projects. But the Central Government has not kept its promise. It is because the Recruitment Board for this Organisation is located in Bombay and persons belonging to other States have been given priority in
Private Members' Resolution 400
employment in this Organisation setting aside the promise given by the Government. Government should take immediate action in this matter otherwise the youths in the district would get frustrated. The Recruitment Board should be shifted to Kalpakkam immediately so that the local people could be provided with employment in this Organisation.
Sir, Tamil Nadu has a long coastal area and production of salt under small scale could be given importance not only in the production of kitchen salt but also for salts that are used in the production of lifesaving drugs can be considered. Necessary financial help could be extended for this purpose and coastal areas should be reserved for it. Likewise, Government should come forward to provide all facilities to fishermen by making provision for unsophisticated technology for processing marine products so that they could be exported and foreign exchange could be earned. A lot of cashew nut is produced in my constituency. Small industries could also be set up for the production of cashew nut and extraction of oil.
Sir, my constituency consists of six Divisions. Out of this, two have already been declared as backward and other four Divisions are yet to be declared as backward. I would request the Government to issue orders declaring these four Divisions Thirupporur, Chengalpattu, Acharappakkam, Uthiramerur also as backward so that all facilities including financial help may be provided on priority basis.
Sir, NRIs may also be entertained in my constituency since Chengalpattu is adjoining Chenai, the capital of Tamil Nadu. Moreover, under Jawahar Rojgar Yojana more funds should be provided for agricultural labourers. Under PMRY scheme, each educated unemployed youth may be given a loan amount of rupees one lakh through public sector banks. But the bank authorities are creating a lot of problems by insisting security from these youths. Whereas we have been receiving complaints that banks are giving loan to certain persons without much fanfare and are thus showing partiality.
I would urge upon the Government to instruct the Banks to provide loans to all, without showing any partiality to anybody, whoever he may be. Two decades ago, Tamil Nadu was number two in the country in industrial advancement. Now, the State has slided down to the 14th place. All this is due to this neglect of the State's interests by the centre at various stages. With the Centre's kind and considerate attention to the State now, I believe that Tamil Nadu can definitely go ck to its original position in industrial advancement. The State Government in Tamil Nadu is taking all steps to provide employment to the downtrodeen and weaker sections.
401 Private Members' Resolution
With these words I conclude.
DR. ASIM BALA (Navadwip): Mr. Deputy-Speaker, Sir, unemployment problem is very acute in the country. This is the reason why large number of unemployed youth are taking to anti-social activities. They think that this is the only way in which they can manage to live when they do not get any employment. This is a very serious thing that is happening in the country affecting our social environment.
If the unemployment problem is to be solved, it has to be dealt with on priority basis. We must support the Government sector, public sector, private sector, big industries, medium and small industries, tiny indutries. and cottage industries which provide more employment in the rural areas where reside a large number of unemployed youth.
If we take the agriculture sector, workers are not provided full employment there. We do not have a proper plan to increase employment opportunities in agricultural sector for the unemployed youth. Apart from agriculture, there are fisheries, sericulture, fruit and vegetable cultivation, and horticulture which are all important areas of employment generation.
To generate employment it is very essential to develop infrastructure. Another area where we are lacking is rural roads. If we do not have proper roads, the communication systems will not work properly. Large sections of people are provided jobs if roads are laid up to the remote corners of the villages.
Railway line is another essential factor for employment generation. We the Members of Parliament keep demanding for railway lines because once a railway line is laid in an area several employment avenues open up. These are the important areas we have to concentrate on to combat the problem of unemployment.
We have to see which sector is best suited for a particular job. If you take the example of livestock, about 73 per cent of the rural population traditionally depend on livestock.
But if we have to take some scientific method to give training, it will provide employment to a large section of population of our country. This could solve especially protein and nutrition problem, among other things. This is in case of fishery. In my area, we have a large number of ponds. They have not been utilised. For rearing fish, we have to have a small number of cooperatives in a particular locality. Through cooperatives, we can run fisheries for a particular pond or for a particular area or for livestock or for poultry or for
Private Members' Resolution 402.
dairy or for bee or for so many things. Why am I giving more emphasis on livestock, especially goat rearing because the poorest of the poor people are rearing goats, if a family is having four or ten goats, that family can survive for the whole year. There is a shortage of funds everywhere. When we are searching for employment or anything, we can hear the hue and cry that there is no fund. How could we solve this problem The planner should think about how to get the fund, infrastructure facilities to solve the problem of
As regards self-employment, some type of training system or procedure, training institution, small or big. even in the town, in the rural areas, is to be set up in different parts of the country. What happens after training? After the completion of the training they are not getting any help from any Bank or any other financial institutions for setting up their own business. They could not move, because they are not getting proper resources. Even in our Banks and other LIC and GIC Institutions, they are not giving proper help. Sometimes, GIC, Banks are coming up but there is some nexus between the officers and some bad people. In this sector if you take a very pragmatic plan and implement, then at least we can solve some of the unemployment. With these words, complete my speech.
SHRI KALPANATH RAI (Ghodi): First of all I want to thank Shri Prabhu Dayal Katheria for moving this resolution in the House which deals with the problems of unemployment. This is the one question on which the entire Parliament should devote, if possible, a week's time to discuss this problem and during the course of discussion apart from Members of Parliament all the Cabinet Ministers and even Prime Minister should be present in the House Problem of unemployment is the biggest problem of country. Our Members of Parliament, can not go back to their areas. If they go back to their areas they are surrounded by thousands of educated youth. Their parents also surround them to tell them that their wards are engineer, overseer or engineer in electronics and hence they should be given employment. Today the problem of unemployment has worsened to such an extent that lakhs of engineers and overseers are unemployed. Even Diploma Engineers and Degree Engineers are unemployed.
Today names of about five crore un registered with the Employment Excl country. Apart from them there are about people who are unemployed. Today o population of the country there are abou persons who are healthy and can dc
403 Private Members' Resolution
they are without jobs. If 20 crore manpower of a country is not utilized how the country could become powerful. It has been said :
"With a view to check increasing unemployment and for generating more employment opportunities, this House urges upon the Government to
(i) provide financial assistance to existing small scale industries:
(ii) set up new small scale industries and provide necessary infrastructural facilities like loans, electricity. marketing, etc. to such industries;
(iii) reserve certain areas of production for small scale industries; and
(iv) set up a National Craftsman Development Bank." [Translation]
It has been stated that infrastructure should be created for these things. I would request all the members that today we need smaller industries in our country, we need medium sized industries, we need big industries, we have to manage smaller private sector industries or we want to manage Public Sector Units, we need power to run all these industries. There is power crisis in all parts of the country today. There is power crisis in U.P., Bihar, West Bengal, Orissa, Punjab. Sir, your Haryana is also facing power crisis. The entire country is facing power crisis. If electricity is not available industries cannot be run in the country and it we are not able to run Industry the unemployed would not get any work.
Sir, during the period of the Seventh Five Year Plan, when Shri Rajiv Gandhi was the Prime Minister it was decided to generate 22000 M.W. Electricity during 7th Five Year Plan. For the first time in the history of India 22 thousand M.W. Electricity was generated in the Seventh Five Year Plan. When in the year 1988 Shri Rajiv Gandhi got prepared an Approach Paper in consultation with Planning Commission for the Eight Five Year Plan, it was stated therein that India would need 48000 M.W. Electricity during the 8th Five Year Plan. Planning Commission pointed out that resources required for generating such a quantity of power are not available with the government. It should therefore be sealed down. Then it was decided during the year 1989 hat 38 thousand M.W. Power would be generated during 8th Five Year Plan. Elections were held during the year 1989 and a government was formed. This government becontinued in the country upto June 1991, but generation
electricity could not increase in our country during
Private Members' Resolution 404
those two years. Then another government came into existence during 1991. This government prepared a Blue print of the Eighth Five Year Plan and it was decided in consultation with all the Chief Ministers in the country as well as Members of the Planning Commission that resources were not available for generation of 48 thousand M.W. Electricity. Therefore 38 thousand M.W. Electricity would be produced during the Eighth Five Year Plan. Sir, Eighth Five Year Plan is close to end and we have been able to generate only 15-16 thousand M.W. Electricity during this period. With such a slow pace of generation how can we achieve the targets of our national growth, our small and medium industries would flourish how Private & Public Sector Undertakings could do any work and how crores of unemployed people in the country could get employment? This is a question on which we should have national consensus. There should be a nationwide discussion on this amongst all the hon. Members. All the 542 Members of Parliament should express their views about this and a national consensus should be formed on the basis of these views and Planning Commission should formulate its schemes on the basis of those views.
Sir, all Members of Parliament are aware of the conditions prevailing in villages. If today a tractor goes aut of order in villages no mechanic is available to repair the same. If a tubewell goes out of order there is no one to repair the same. There is no engineer available to attend complaints regarding electricity. Industrialisation is taking place in India at a great pace. Liberalisation is taking place and country is entering into industrial age. Therefore we need technically educated people. We will find 50-100 Graduate and Post-graduate in each village but you will not find even a single person to repair tractor, tubewell or electrical fuse. I am therefore to say that Planning Commission should make provision only for job related and job-oriented education after High School. Polytechnics and ITI's should therefore be opened in each block of the country. Only brilliant and toppers may go for graduation and post-graduation and all others may be provided technical education.
DR. ASIM BALA: Don't talk of stopping education.
SHRI KALPNATH RAI I am not making a demand to stop education. If you listen carefully you will know that I am talking of job-related and joboriented education.
Sir, what is happening today is that graduates and post-graudates are not able to secure clerical jobs. In my district about 10 thousand graduates and postgraduates appeared for 60 posts of Accountants.
405 Private Members' Resolution
SHRI RAJENDRA AGNIHOTRI (Jhansi): How much money was spent on it.
SHRI KALPNATH RAI: The question of money is a separate matter ...(Interruptions)
PROF. RASA SINGH RAWAT: This is a result of wrong policies pursued by those who held reign of power during all those years since independence. ...(Interruption)
SHRI KALPNATH RAI: If you talk on that point and start reasoning I will say certain such things that you will become quite. You talk of national consensus. I am talking of national consesus. I am not interested in mud slinging unnecessarily.
SHRI OM PAL SINGH 'NIDAR': This is alright. But now move further from national consensus.
SHRI KALPNATH RAI : We alone can not solve the problem. You are our friend. We are all Members of Parliament. All have problems. I am talking of the problems which they come across as Members of Parliament. I am a very busy person. I go from village to village and this is the reasons that I have again been elected as a Member with your prayers.
MR. DEPUTY SPEAKER : Shri Kalpnath Rai : Now come to the point.
SHRI KALPANATH RAI: Sir, may I request through you and convey my thanks to the Members who has moved the Resolution.
We have to consider that is the the greatest crisis before our country today. Today condition about irrigation facilities in the country is very bad. Through Shri Rawat I would like to submit that our country should provide highest priority to power generation in our country. People automatically setup Industries when power is available. Where electricity is not available there people who had taken loans are today facing financial crisis. They have migrated to Calcutta because whatever money they had has been ruined. 90 per cent of those who had taken loans for setting up small scale Industries are facing crisis, because their Industries have been ruined due to non-availability of power. They are running in losses. Hence, if the electricity problem is to the solved in the country, I request the government that the Planning Commission and the Central Cabinet should fix high target of power generation for the 9th Plan period and Members of Parliament should exert pressure on the government in this regard. We should fix a target to generate power in 9th Plan as per requirements.
Sir, today the country is also facing problem of
Private Members' Resolution 406
environment. It has today become a matter of concern in whole of the world. 33 percent of the land area in India should be under forests. Today we are facing a lot of problems because of less forest coverage. Forest coverage in the country has come down to 1112 percent. The Government should form a Land Army in the country consisting of 10 lakh youths. They should be provided training and entrustrd with the responsibility to plant trees on waste lands, on river banks and roads sides in order to improve environment. This land army should also be entrusted with the task of making 75 per cent unirrigated land in the country irrigable.
Sir, there are big rivers in our country. Certain areas in our country are as such where there is severe shortage of water in certain areas. Tamil Nadu and Karnataka are today fighting over water. There is water crisis before Punjab and Haryana. Rajasthan and Punjab are fighting over water. There are strikes in a number of States in country over question of drinking water. How to solve this problem. In India we have two sources for water, either through Rivers or through melting of ice. Hence water should be utilized for making India a prosperous country, for irrigation purposes, for drinking water purposes. Land Army consisting 10 lakh people should make efforts in this regard. Water from all the Rivers of India should be treated as a national assets. It does not belong to one Province but to the whole of country. The constitution of India should be amended in such a manner that all the countrymen get equal share of water. You may amend the constitution for this purposes, if so necessary. A National Scheme should be drawn up and arrangements should be made through Land Army. Greatest need is to generate power during Ninth Five Year Plan in order to solve problem of environment, provision of water for all the fields, to provide jobs to every body. The next steps we have to take up is that the government should set
at every district head quarters in the country a Krishi Science Centre, an I.T.I. and a Polytechnic and ITI and Polytechnic should be opened at Block level as well.
We should plan in such a manner so that we could find out the number of people we may be able to provide jobs during ninth plan period. Manpower should be trained as per requirements so that children could be provided the jobs as soon as they leave school. Problem of unemployment is increasing every day.
I want to say something about Members of Parliament. About 75 percent contestants had lost the elections held in 1989. These elections were held in 1991. 330 constituents, who were members earlier have lost elections during the recent elections. Wherever we go people ask as whether elections are going to be held early. The life of the Parliament should continue
407 Private Members' Resolution
upto 5 years. Members of Parliament are under attack from all sides. The whole political system is under attack.
All the beaurocrates in the country those who become IAS whatever government is there the services of these officers are not terminated. Judges of the judiciary also continue in their position. But politicians are under attack. I want to ask those persons that when fight for independence of India was being fought, how many Judges participated in the same, how many beaurocrates participated in that struggle? They were serving the Britishes till 12.00 in the night of 14th August. Crores of people participated in the struggle for freedom of the country, lakhs of people made sacrifices and got freedom from the country. That very freedom gave us Democracy. And in that democracy to-day our party may come to power and to-morrow some other party may come to power. This is not a bad thing but the regular attacks that we are witnessing on this democratic system are not good. I can say with challenge, we may be having difference of opinion amongst us, those who do wrong things may be punished by people. People are elected to Parliament after lot of sacrifices in the life. If the Parliament is dissolved early a number of M.P's do not get re-elected. Most of the people are elected as M.P. 2-3 times during whole of their life. There are hardly 2-3 per cent who are elected as M.P. 5-6 times. They will remain leaders whether they win elections or not but those who lose elections after remaining M.P. 1-2 times whether anybody consider any thing about them? Had Prime Minister been present here I would have asked him whether any concern is shown towards their plight?
If you come to my place at 9.00 a.m. you will see the number of people coming from Bihar, U.P., etc. to me to seek my help. I listen to them every day and then I have to write letters for their works. I have to make telephone calls. Sometimes I have to go to Ministers. You may imagin the sacrifice one has to make to get ticket from a party and become a Member of Parliament for 1-2 terms. There are good people as well as bad people in our country. In judiciary also there are good as well as bad people. Beaurocracy also consists of good as well as bad people. Society also, in 90 crores people also there are good as well as bad people. But raising fingers against one category is a conspiracy to finish democracy.
Parliamentary Democracy system is the best system even today. Democracy is the best system. The foundation of which system was laid by Mahatma Gandhi and freedom fighters who fought for freedom of our country is to-days also the best system of governance. It is our responsibility to strengthen that system and end social and economic exploitation in
Private Members' Resolution 408
India through Democracy, to prepare crores of people of the country for making this nation strong and powerful. We have been elected to this sovereign Parliament as its member to fulfill this responsibility. I would like to fecilitate all the Members of Parliament. Whichever party they may belong to. Today the country has reached such a stage where we have to reach national consensus about problems before, the Nation. ....(Interruptions)
MR. DEPUTY SPEAKER : Shri Kalpanath Rai I have seven names with me.
SHRI KALPNATH RAI : I will take one minute. Our population is continuously going up at a great pace and we the leaders of India are not able to make a law in this country in this regard. We do not take correct decision under pressures, due to policy of appeasement. China today is facing such a situation that the number of females has gone up in comparison to males. The Government of China has announced that those who will give birth to male children would be rewarded by the Government. In Malaysia (Interruptions)
MR. DEPUTY SPEAKER: How this is relevant to this Resolution?
SHRI KALPNATH RAI : Resolution is relevant in this way that if Family Planning Programme is not implemented in the country on war footing the number of unemployed may go upto such an extent that it may not be possible to give employment to them. Hence the Government should consider formulating a national population policy, an integrated economic policy and employment scheme for 90 crore people of the country based on National Consensus to be arrived at through Members of Parliament to make India a strong country. ....(Interruptions)
MR. DEPUTY-SPEAKER: You can not say much in this regard. Be seated.
SHRI S.P. JAISWAL (Varanasi): Leaving one you felicitate others....(Interruptions)
SHRI NAKLI SINGH (Saharanpur) Sir, I have been elected from Saharanpur for the first time. I congratulate you to have given me a chance to speak ....(Interruptions)
MR. DEPUTY SPEAKER : There is nothing to congratulate in this. You can thank me.
SHRI NAKLI SINGH: I thank you. The Resolution moved by my friend Shri Prabhu Dayal Katheria is liked by everybody in the country.
The population of the country nearing 100 crores
409 Private Members' Resolution
and the country is facing a serious crisis of unemployment. There are a number of countries in the world where population is less than the number of unemployed in this country. This is a very serious problem before our country. It is a pity that inspite of this resolution being very good and speakers being very good the number of people sitting here is very samll.
Why this charkha was given to us by Reverand Mahatma Gandhi? What was there in his mind when he was thinking of Swaraj? He had this in his mind that Small, Cottage and Agricultural Industries would prosper in this country. He worked in this direction. But what we find today is that today Bata is the biggest shoe maker in India. Similarly biggest blacksmith in the country is Tata. We are unable to understand whether this is the way we are fulfilling the dreams of our Policy Makers and helmsmen of our country. Whichever party is running the Government those things should not be allowed to be manufactured by Big Industries which can be manufactured by small scale and cottage industries. Cottage industries, small scale industries and agricultural based industries should therefore be encouraged and manufacture of such items by big industries should be banned. What we find todays is that items manufactured by small scale industries are finding it difficult to compete with items produced by big industries.
There are potters in villages which are called Prajapati. If they are provided loans and other facilities they can manufacture many good crockery. What we find today is that agricultural implements such as weeding hooks are being manufactured by big industries in large scale. If such things continue where poor blacksmiths of the country would go, where our weavers would go. You see how much the number of Jhompries has increased in our big cities. People come to cities in search of employment wherever they are themselves skilled. They don't have any work in villages, they do not get any employment. Hence they migrate to cities. A day may come when no one would be left in villages.
Rural people have lot of time at their disposal. During earlier days people belonging to Kahar Caste used to make baskets but today they do not possess enough money to do this work. It is also correct that there is power shortage. The Government should provide facilities to rural people. Our population is about 90 crores. If this situation continues then what would be future of this country, we can well understand? People should therefore be provided with work. Cottage industries should be encouraged in this country. Big industries should be set up at those places where population is less. Our labourers have not much work. They should therefore be provided protection, financial assistance should be provided to them. Cottage indusPrivate Members' Resolution 410
tries and small scale industries should be set up on large scale in this country. It will help in removing unemployment and create such a condition in the country where people will learn to live with dignity.
Big bungalows are constructed in cities, but these big bungalows and 20-25 storey buildings are constructed by our labourers who come from villages and a number of times some people die from fall during construction period. But when the construction has been completed. 'No admission' boards are hung on the doors of these buildings. Our faces do not undergo much change even if we continue living in cities for 20 years. If one does not get respect, does not get economic security, cottage industries may not prosper.
Dhaka Musline produced in our country was known the world over. At no other place in the world such a fine cloth could be produced. Iron Pillar belonging to Mahabharat age is standing here which has not got rust even today. It shows that there is no dearth of talent in our country, but unemployment would increase in country with the coming of foreign companies to this country. I support this resolution and request the Government that serious consideration may be given to this resolution and such a resolution should be brought by the Government and implemented so that problem of employment in the country is solved once for all.
SHRI RAJENDRA AGNIHOTRI: Sir, I praise my colleague who has presented this resolution. I had tears in my eyes when this resolution was moved. After such a long of independence there are such big areas in the country which are bigger in area and population in comparison to Kerala, Punjab and Haryana which abound in natural resources and manpower and today these areas are facing regional imbalance. I would like to cite examples in this regard. Bundelkhand area consists of 17 districts 5 districts from part of U.P. and balance 12 districts from part, of Madhya Pradesh. Today if the the area is afflicted by stravation and poverty and shortage of drinking water, what are the reasons for the same. The main reason for this condition is that youth of the area are unemployed. What is unemployment? Unemployment does not fall from the sky or it does not take birth from womb. This unemployment is such a system which is created by Society or State in its areas. Sometimes such things come before mind that one feels to revolt against system of Government.
Today agitations are being conducted at a number of smaller places in the country for creation of separate States, be it Uttaranchal in U.P. or Varanchal of Bihar. Similarly agitation is being conducted for creation of separate Bundelkhand State from U.P. and Madhya Pradesh. I think that agitation for creation of a sepa411 Private Members' Resolution
rate State Bundelkhand is the oldest agitation for creation of a separate State. I represent Jhansi, Lalitpur Parliamentary Con tuency and when I tour my constituency I do not get sleep during nights. Inspite of that we possess forest resources, inspite of fertile land being available large number of people in villages are without road, cloth and shelter over their heads. Bundelkhand is such area where people do not get drinking water for 4 months in a year. They have to drink water from dirty nallahs. What is the reason for this state of affairs. Inspite of such a long period of Government, be it a State Government or Delhi Government, it has not been possible to solve the problem of drinking water to 3.5 crore people of these 17 districts inspite of spending lot of money and planning. For four months they have to drink water from dirty Nallahs.
I am pained to say that people of Bundelkhand have to live on Mahua only for 4 months in a year. They possess forest resources, there are deposits of gold and silver in the region. In addition valuable minerals are available in Bundelkhand region. Lakhs of rupees are earned through this forest resources but this wealth is going to Lucknow and Bhopal where big majestic buildings are being constructed, but there is shortage of water in Bundelkhand.
Sir, want to say that there are no Industries in 17 districts forming Bundelkhand. This area is bereft of Industries. In view of the situation prevailing there Agriculture based industries should be set up there. Industries based on natural resources should be set up there, but there is not a single industry in these areas of Bundelkhand. I want to tell you that the reason for employment in Bundelkhand area is not that youth of the area are not strengthy enough. They have strength in their arms, they have intellect but they are unemployed. I therefore want to say that if farmers of Bundelkhand area are provided with water in their fields, industries can be set up in the area and life in youth could change. Our fields are dry and not producing anything. The situation in Bundelkhand being such no capital formation is taking place there. The area in which there is no capital formation, how the youth of the area will get jobs. When there is no capital formation there will be unemployment in the area and there will be poverty. I want to raise this question in this House today that problem of unemployment is not going to be solved in this manner. I have been elected to this House for the third time. I have been a member of Legislative Assembly as well. I have heard the speech of Prime Minister. He cited the example of Karnataka and said that he provided drinking water facilities to the poorer people there. He described what he had done for development of small scale industries there. We are
Private Members' Resolution 412
discussing Budget in the House. On one hand foreign companies are being permitted to set up industries in India while on the other hand poverty has caught hold of the country and youth of the country do not have any work to do. Moreover there is no spread of education in the country. There are no schools in a area of 10-15 km., no High School exists in 20-25 km. area and no Dispensaries in an area of 10-15 km. We are discussing Budget in the House but no provision is being made for the development of such areas. This is not my agony only. I am presenting agony and pain of the people of the area before the House so that the State Govt. ad the Central Govt. could invest in the development of the area. I want to say that a Backward Development Board may be set up exclusively for the area which abound in wealth and the said Board may take steps to set up small scale Agriculture based Industries in the area in order to alleviate poverty and unemployment in the area. We are not interested in foreign Companies to come and develop those areas. We need means, we need capital when we have these things, we have youth with us we can set up Agriculture based Industries. I can say this certainly that we are in a position to set up such industries at our own, such big areas can contribute a lot for creation of capital in the country. In fact there is a saying that the capital will flow downward.
MR. DEPUTY SPEAKER : Mr Agnihotri, one hour was allotted for this and it appears that is also over. Many more names are there with me in the list. Therefore if the House wishes it may extend it by one hour more...(Interruptions)
SHRI AMAR PAL SINGH: Yes, Sir, it may be extended by one hour more... (Interruptions) Time for General Budget is allotted from 6.00 p.m. onwards.
MR. DEPUTY SPEAKER Yes, then it may be taken to next week.
SHRI RAJENDRA AGNIHOTRI: Sir, I need half an hour more to speak. I require half an hour more to express my feelings.
MR. DEPUTY SPEAKER : You will get this time next time......(Interruptions)
SHRI AMAR PAL SINGH: Sir, time for general budget is allotted 6.00 onwards.
MR. DEPUTY SPEAKER: What is the Consensus of the House. I want to know whether the time is to be extended.
SHRI RAJENDRA AGNIHOTRI: Sir, take up the Budget at 6.00.
413 Private Members' Resolution
MR. DEPUTY-SPEAKER: It will start at 6.00.
SHRI AMAR PAL SINGH: Postpone it to meet Friday.
MR. DEPUTY-SPEAKER : Time for this topic is extended by one hour more. We will continue the discussion next time. Budget will be taken up at 6.00. SHRI RAJENDRA AGNIHOTRI : Sir, the main reason for the present unemployment is the Regional imbalances in the country. The strength of the youth is not being put to use. It is going waste. They are sitting idle. Sons of farmers are without work. Mr. Rai was just mentioning that if a tractor goes out of orders there is nobody available in villages to repair the tractor. If a cycles goes out of order there is none to repair the same and this is a country of villages. When there is no prosperity in villages how you can remove unemployment from the country If farmers in the country are not prosperous how economic machinery of the country can become strong. How you can remove unemployment from amongst youth of the country? How factories can run without problems in the country. When
was a student our teacher used to tell us what is produced by farmers. Farmer grows wheat. He grows corn, sugarcane, kapas, oilseeds. But when his produce goes in the hands of foreign powers, it goes in the hands of big Capitalists they become owners of property worth crores of rupees and the farmers who toil hard, has no cloth to wear. He has no prosperity. He does not get even meals for two times. If he falls ill, he has no money for his treatment. Today our farmers are not prosperous, because whatever he produces he does not get proper money for the same and when he does not get proper money he has no money in his pocket. If he has no money in his pocket who is going to purchase the things produced by small scale industries in the country? When the farmer has no money there will be no body to purchase the things produced by industries.
The whole planning system is faulty. Sir, I want to say that when we discuss while sitting in this great court the youth of India also participate in the discussion. But he can not make arrangements for his meals, he cannot arrange for drinking water throughout the year, he can arrange for his medicines when he falls ill. When he moves in cities in search of employment he does not command any respect. He goes back to villages. The feelings he gets does not provide any proper directions.
MR. DEPUTY-SPEAKER: Shri Agnihotri you may continue next time.
Now we will resume discussion on General Budget.
General Budget 414
GENERAL BUDGET 1996-97
GENERAL DISCUSSION
SHRI AMAR PAL SINGH (Meerut) I want to draw the attention of the hon. Minister towards Alternative Resources of Power. 80 lakh vehicles are running today in the world successfully with power alcohal. Brazil is the example in this regard. Experiments in our country are also being conducted since 1980 in Indian Institute of Petroleum at Dehra Dun for use of Alcohol. So far alcohol mixed vehicles have covered distance of 42 lakh k.m. It has been observed that efficiency of the engines increases with the use of alcohol, emission of smoke is less. I request the hon. Minister that a Relief Scheme may be drawn up to increase production of Power Alcohol. Sugarcane producers may also benefit from this scheme and import of petrol may also come down and there will be a saving of foreign exchange.
Exports in our country are being over invoiced and imports are being under invoiced. I am citing an example in this regard. Our industrialists are sending their money abroad through Hawala on 7 per cent commission and these companies evade Income Tax on the money by showing fake exports and they further avail Government incentives for export promotion. In software sector un-used floppies are being exported. No programmes are being exported. I would suggest to hon. Finance Minister that there is more need to activate Revenue Intelligence wing so that the country could be saved from over-invoicing of exports, under-invoicing of imports and fake exports.
Hon. Finance Minister has increased the allocation by 33 per cent for Police and Para Military forces. An additional provision of Rs. 950 crores has been made. Allocation for Police Force has now gone upto Rs. 4368.47 crores. Hon. Finance Minister has raised 37 crores in allocation for SPG engaged in providing security to ex-Prime Minister whereas allocation for Armed Forces have only been increased by 0.3 per cent. Keeping in view the rate of inflation increased allocation of Rs. 970 crores on Defence Budget is no increase in fact it is reduced allocations whereas the responsibilities for security of the whole country lies on our armed forces. China and Pakistan are encircling our
415 General Budget
country. China is continuously conducting nuclear experiments and Pakistan has deployed M-11 Missiles on Indian Borders.
China is becoming a Super Power. It has set up an Army Base on Coco Islands oi Mayanmar which are at a distance of 50 nauticle miles only from AndamanNicobar Islands. Inspite of all this the hon. Finance Minister has not paid any attention towards Defence Budget and allocation for Atomic Energy has also been reduced. Sir, through you demand that budget allocation for modernisation of Armed Forces and allocation for Atomic Energy may immediately be raised.
The hon. Finance Minister in his budget speech has talked of giving encouragements of Rs. 30,000 for small tractors and subsidy on fertilizer has also been raised from Rs. 500 crores to Rs. 1724 crores. This is a laudable effort.
I would like to point out to the Government that on the one hand it is divesting farmer of his land by acquiring it and pushing him to unemployment but more than that the farmers are charged Income Tax on the compensation they get for their lands, whereas Income Tax is related to employment and not related to unemployment. I therefore request the Government of India that Income Tax may not be charged from the farmers from the compensation they get for their acquired land though they may not be able to invest the said money from the financial year itself.
THE MINISTER OF FINANCE (SHRI P. CHIDAMBARAM): The translation says: "You are charging income-tax on land acquired from a farmer." Are you sure that statement is correct?
There is no income-tax on land acquired from a farmer. I heard it in translation. I do not know what you said in Hindi.
SHRI AMAR PAL SINGH: Yes.
SHRI P. CHIDAMBARAM : No. Please tell me the Section. I will verify it.
SHRI AMAR PAL SINGH Hon. Minister, I am speaking in the House that income-tax is being charged from the farmer on the amount he gets against his land but which has not been invested in the same financial year.
SHRI P. CHIDAMBARAM I do not want to contradict what the hon. Member has said now. I do not think he is right. I will verify it and come back.
General Budget 416
MR. DEPUTY-SPEAKER You continue your speech.
SHRI P. CHIDAMBARAM It is all right. It is my duty. I will check it.
MR. DEPUTY-SPEAKAR : You go ahead.
SHRI AMAR PAL SINGH: Alright, check it.
Sir, even total on the one hand we are talking in our country about liberal economic policy while on the other hand agriculture based industries such as Sugar Industry are bound by Licences.
SHRI P. CHIDAMBARAM There is no tax. If the hon. Member is saying that agricultural land is acquired and there is capital gains and that is being taxed. I think, I know that part of the law. But I will verify it again. There is no tax. Since he has made a statement, I respect his views. I will check and come back. But until then, I do not want you to say it out. I will check and come back.
SHRI AMAR PAL SINGH: Hon. Minister, in my constituency. Meerut, many farmers are getting money against their land. If they do not invest that money in the same financial year, they have been charged income-tax. I know that.
SHRI AMAR PAL SINGH: I request you that the money which the farmers get against their land when it is acquired by the Government
MR. DEPUTY-SPEAKER: Alt right. He will check it up.
SHRI AMAR PAL SINGH Income-tax should not be charged on that money of the farmer.
Sulphur Khandsari Units with 6 per cent recovery are not permitted Vaccum Boiling. If they are permitted to use Vaccum Pan their recovery rate would go upto 9 per cent. It would not only save three per cent national loss but quality of the sugar would also improve, economic exploitation of the farmer could stop, employment opportunities would arise in rural areas, there will be a saving of Power and these units may
417 General Budget
be able to generate power for their captive use from their boilers.
Small units crushing 5000 quintal sugarcane per day or units with less capacity than this may be exempted from levy. Excise duty can be charged as compound excise duty as was done prior to 1981.
Even today there are restrictions on free movements of agricultural produce from our State to another. I will cite a example in this regard. Molasses are produced from Sugarcane but U.P. Sugar Mill owners are not permitted to take Molasses outside the State and sell the same outside. It is controlled by the State Government. I would request the Finance Minister that all the Central assistance being provided to that State may be stopped which puts restrictions on State's Agriculture produce or produce of agriculture based industries of the State. Our country is not self-reliant in respect of Edible Oils. The Minister of Finance has therefore reduced Import Duty on Edible Oils from 30 per cent to 20 per cent. Our country gained independence 50 years ago and the Government has not been able to convert waste land into agricultural land. I request that all the waste land available in the country should be allotted to progressive farmers in the country so that they could convert the same to agricultural land suitable for pulses and oilseeds cultivation. If the Government substantially increases support prices for oilseeds and pulses the country could become selfreliant in respect of oils and pulses. Even though support price for pulses is Rs. 840/- per quintal yet it is available to consumers today at Rs. 30 per kg. If the support price is raised to Rs. 12000 per quintal the country will become self-reliant in pulses.
Sir, I request the Government that keeping in view the interests of paddy farmers there should be no restrictions on the use of 10 Horse Power Paddy Machine. India is a country of villages. Private Banks, Multinational Companies, big Industrialists had themselves proposed in the FICCI Meeting that each unit may adopt a village to each to develop the same as a Model village. I request that efforts should be made to implement this proposal made by FICCI.
The hon. Finance Minister has proposed tax on such industries which were so far not paying any tax, specially companies such as Reliance and Tata. This is a appreciable step. But Soft Drink Companies such as Pepsi and Coca Cola should also be taxed. Budget figures indicate that 22 per cent money proposed to be raised through additional loans and one per cent through foreign loans. It is an irony that our Defence Budget is nearly 12 per cent whereas 25 per cent provision has been made for repayment of loans taken
General Budget 418
by the country. It is not a good omen for the economy of the country. I am therefore to suggest that all the valuable Government land in Metropolitan Cities, the land belonging to sick units in Metropolitan cities should be disposed immediately through auction and we should strive to repay foreign loans.
Sir, the NRIs who are investing in our country or desirous of making investments should be given citizenship of the country. NRIs who make investments under Double citizenship should be free. Unless small scale industries are given protection and unless family planning is compulsorily introduced in the country. it may not be possible to solve the problem of unemployment in the country. There is no provision in the budget in this regard. I therefore oppose the Budget presented by the hon. Finance Minister ...(Interruptions)
MR. DEPUTY-SPEAKER : Before I name the next speaker I want to inform Shri Sontosh Mohan Dev that Direction No. 115A from Directions by Speaker provides :
"The speaker shall not be bound by the lists or order in which names have been given by Parties or Groups or individuals directly. The lists shall be for his guidance only."
SHRI SONTOSH MOHAN DEV (Silchar): I have full respect for you, Sir, I do not mean or I do not have disrespect for you. I will not dispute with you.
MR. DEPUTY-SPEAKER I have not finished what I have to say.
SHRI SONTOSH MOHAN DEV: You should not take it otherwise. You have got every right. Can we not ask you to help us? It is because I have to deal with so many members.
MR DEPUTY-SPEAKER : Please let me finish.
SHRI SONTOSH MOHAN DEV Sir, I am not questioning your authority. [Translation]
MR. DEPUTY-SPEAKER I have to say something more. The hon. Speaker has directed that I should help Shri Sat Mahajan. I am therefore calling his name
SHRI SAT MAHAJAN (Kangra): Sir, I have taken
419 General Budget
this liberty because I have to catch my train.
Sir, at the outset I would like to congratulate the hon. Finance Minister for the Budget that he has presented. While I am offering bouquets there are, of course, no brickbats, but there are some suggestions -some sweet and some sour.
Sir, I want to start my speech with a couplet by Iqbal.
Sitaron se aage jahan aur bhi hain,
abhi ishaq ke imtihan aur bhi hein, Mohabbat hamein un jawano se hai,
sitaro per jo fenkate hein kamand.
About the budget I would like to say that appearance is good, it has good qualities, but your compulsions are your drawbacks in the budget. 70 bind 13 parties....
Sir, he had to do a very tightrope waling. He has tried to balance it as best as possible. This Parliament had very great traditions of having very good Finance Ministers except, of course, for a brief spell when the concept of planning was given a go-bye and real Plan concept came into being. Otherwise, every Finance Minister had done his best, rather his very best in the formulation of Budgets.
Sir, in this Budget also our Finance Minister has raised the hopes of the people. He has made many promises and tried to throw up an array of dreams economic dreams. His tight rope walking had been excellent. He has proved to be a worthy successor to Dr. Manmohan Singh. But I have a grudge against him. the grudge is that in spite of having inherited such an excellent legacy from Dr. Manmohan Singh he has not mentioned a single word of praise about the legacy and the good work that he did. Dr. Manmohan singh did that under the political will of our leader, Shri Narasimha Rao. He has totally liberalised the whole thing. He should have at least said something for the commendable job that Dr. Manmohan Singh did.
Sir, I must also congratulate the Finance Minister for his guts to state that he would stick to the reform process that had been initiated by Dr. Manmohan Singh and they would not be reversed. The reforms include privatisation. liberalisation and globalisation. He has tried to carry forward the reforms process. He has
General Budget 420
promised this House that the foreign investment to the tune of Rs. 10 billion dollars would flow into this country. It is possible because the ground for it had been prepared by Dr. Manmohan Singh. So, courtesy demanded that he should at least have praised his predecessor, who is no less an economist than anybody in this country.
Sir, our Finance Minister has made many innovations in this Budget and I congratulate him for that. He has said that money has been allotted for development of new Infrastructural facilities which were very badly needed and has laid emphasis towards strengthening the existing infrastructure. He has promised the constitution of a high level Commission on Expenditure Management which would submit its report within six months. I hope. he sticks to this schedule.
Sir, he also has promised that he would bring in a comprehensive Bill on BIFR and SICA, the provisions of which have become outdated. I am very happy that he has gone in for this. It is because our industrial growth has gone up to 14 per cent and it should not be allowed to come down. Our agricultural growth is 0.9 per cent. I would like to make a suggestion through you that the recommendations of the BIFR should be made mandatory. Otherwise, they have no value. Unless that is done, BIFR and SICA would be of no use. As you are going to bring in a comprehensive Bill on this, I am making this suggestion.
Sir, it is said that well begun is half done. He has made an attempt to strengthen the NABARD. The allocation for NABARD has been doubled this time in the Budget.
The hon. Minister has given the concept of IRDF and DFSC. An amount of Rs. 500 crore will come from the Government, Rs. 500 crore from the RBI and Rs. 4000 crore will be contributed by the private sector and other sectors. That is very good, and that will help the rural economy also.
The recommendations of the Members of Parliament in the District Committees are not carried out. What is the use of these District Committees when their recommendations are thrown into waste paper baskets. To start with the Development Commissioner does not take action on them, and secondly, the Banks do not consider them. A minimum of 10 per cent to 15 per cent recommendations only are carried out. The poor farmer totally gets exhausted. The hon. Minister
has proposed that he would help the kisan. The kisąn does not understand the mechanics of banking. If you really want to help the poor farmer, please make the procedures simpler so that he can understand them and
|
english
|
Dame Anna Wintour is widely regarded as one of the most powerful women in the fashion industry, with a reputation for defining trends and nurturing fresh talent.
She has been the editor-in-chief of Vogue magazine for the past 30 years, and she was designated artistic director of Condé Nast Publications in 2013. Since 1995, Wintour has presided over the Met Gala, one of the most renowned events on the fashion calendar.
The Queen of England named Wintour a Dame in 2017 for her contributions to media and fashion.
Anna Wintour was born in Hampstead, London, to Charles Wintour, the editor of the Evening Standard, and Eleanor “Nonie” Trego Baker, the daughter of a Harvard Law School professor. Her parents divorced in 1979 after marrying in 1940.
She started wearing her hair in a bob when she was 14 years old. She became interested in fashion after watching Cathy McGowan on ‘Ready Steady Go! ’ and receiving copies of Seventeen from her grandmother in the United States.
“Growing up in London in the 1960s, you’d have had to have Irving Penn’s bag over your head not to notice something exceptional was going on in fashion. ” Her stepmother is Audrey Slaughter, a magazine editor who launched publications such as Honey and Petticoat.
Her fashion journalism career began in two British magazines. She later relocated to the United States, where she worked at New York and House & Garden. Between 1985 to 1987, she was the editor of British Vogue in London. A year later, she took over the franchise’s magazine in New York, revitalising what many considered a dormant publication.
In 2014, she organised the fashion industry’s involvement in Born Free Africa, an initiative dedicated to eliminating HIV transmission from mother to child.
Lauren Weisberger, a former personal assistant, penned the 2003 bestselling novel The Devil Wears Prada, which was later adapted into a successful 2006 film starring Meryl Streep as Miranda Priestly, a fashion editor who is thought to be based on Wintour. Another film, R. J. Cutler’s documentary The September Issue, focused on Wintour in 2009.
|
english
|
package org.artifactory.ui.rest.service.admin.security.crowdsso;
import org.apache.commons.lang.StringUtils;
import org.artifactory.addon.AddonsManager;
import org.artifactory.addon.crowd.CrowdAddon;
import org.artifactory.addon.crowd.CrowdExtGroup;
import org.artifactory.api.config.CentralConfigService;
import org.artifactory.api.context.ContextHelper;
import org.artifactory.api.security.UserGroupService;
import org.artifactory.factory.InfoFactory;
import org.artifactory.factory.InfoFactoryHolder;
import org.artifactory.rest.common.service.ArtifactoryRestRequest;
import org.artifactory.rest.common.service.RestResponse;
import org.artifactory.rest.common.service.RestService;
import org.artifactory.security.GroupInfo;
import org.artifactory.security.MutableGroupInfo;
import org.artifactory.ui.rest.model.admin.security.crowdsso.CrowdGroupModel;
import org.artifactory.ui.rest.model.admin.security.crowdsso.CrowdGroupsModel;
import org.artifactory.ui.rest.model.admin.security.crowdsso.CrowdIntegration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author <NAME>
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class RefreshCrowdGroupsService implements RestService {
private static final Logger log = LoggerFactory.getLogger(RefreshCrowdGroupsService.class);
@Autowired
CentralConfigService centralConfigService;
@Autowired
UserGroupService userGroupService;
@Override
public void execute(ArtifactoryRestRequest request, RestResponse response) {
String userName = request.getPathParamByKey("name");
// fetch crowd groups
CrowdGroupsModel crowdGroupsModels = fetchCrowdGroups(request, response, userName);
if (crowdGroupsModels != null) {
if(crowdGroupsModels.getCrowdGroupModels().isEmpty()){
if (StringUtils.isBlank(userName)){
response.warn("No group found");
}else{
response.warn("No group found for filter: " + userName);
}
}
// update response with model
response.iModel(crowdGroupsModels);
}
}
/**
* fetch crowd groups
*
* @param artifactoryRequest - encapsulate data related to request
* @param artifactoryResponse - encapsulate data require for response
* @param userName - user name
*/
private CrowdGroupsModel fetchCrowdGroups(ArtifactoryRestRequest artifactoryRequest,
RestResponse artifactoryResponse,
String userName) {
AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
CrowdAddon ssoAddon = addonsManager.addonByType(CrowdAddon.class);
Set<CrowdExtGroup> groups;
try {
CrowdIntegration crowdIntegration = (CrowdIntegration) artifactoryRequest.getImodel();
groups = ssoAddon.findCrowdExtGroups(userName, crowdIntegration);
} catch (Exception e) {
artifactoryResponse.error(e.getMessage());
return null;
}
updateGroupExistInArtifactory(groups);
List<CrowdGroupModel> list = new ArrayList<>();
groups.forEach(group -> list.add(new CrowdGroupModel(group)));
CrowdGroupsModel crowdGroupsModel = new CrowdGroupsModel();
crowdGroupsModel.getCrowdGroupModels().addAll(list);
return crowdGroupsModel;
}
/**
* update exist in artifactory flag data
*
* @param groups - crowd group
*/
private void updateGroupExistInArtifactory(Set<CrowdExtGroup> groups) {
if (!groups.isEmpty()) {
InfoFactory factory = InfoFactoryHolder.get();
List<GroupInfo> artifactoryExternalGroups = userGroupService.getAllExternalGroups();
for (CrowdExtGroup group : groups) {
MutableGroupInfo groupToFind = factory.createGroup(group.getGroupName());
if (artifactoryExternalGroups.contains(groupToFind)) {
group.setExistsInArtifactory(true);
}
}
}
}
}
|
java
|
<reponame>codeblindorg/wysiwyg-chrome-app
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('builder.html', {
'outerBounds': {
'width': screen.width,
'height': screen.height
}
});
});
|
javascript
|
package demo.thanhbc.com.popularmovies.pojo;
import java.util.ArrayList;
import java.util.List;
public class Result {
public Boolean adult;
public String backdrop_path;
public List<Integer> genre_ids = new ArrayList<Integer>();
public Integer id;
public String original_language;
public String original_title;
public String overview;
public String release_date;
public String poster_path;
public Float popularity;
public String title;
public Boolean video;
public Float vote_average;
public Integer vote_count;
}
|
java
|
However, 1xBet is apprehensive about its purchasers and continues to pay the full withholding Tax on Betting winnings for them. Thus, when inserting bets on 1xBet, you presumably can make positive that your winnings shall be paid in full, and the bookmaker will take care of paying the tax, as earlier than. Here, in 1xBet Zambia you want to play the bonus quantity only 5 events and at a minimum odd 1.40. However, there’s another, fairly particular, requirement – you should play this bonus amount by placing accrued bets where in a single wager slip you mix three or greater than three bets. A transient stroll throughout the rest of this company’s pages inside the official website will present you that a registration proper here will provide you with greater than just a good sport betting service.
The website’s FAQ section signifies that it takes this step to stop fraudulent activity, however many online evaluations have solid doubt on that rationalization. In order to fully orient on this procedure, discover out more about my personal experience with withdrawals by way of the betting house’s apps. You can discover the Casino tab on the bookmaker’s official website, which accommodates distinctive gambling actions. Any slots on line on line casino on 1xBet is sweet leisure that requires no prior game evaluation.
To end up at the top of the leaderboard and win a automotive, you must place the very best possible bets on the daily accumulators. In addition, there might be an odds increase for 3 selected occasions every day. Nevertheless, the betting supplier doesn’t forget its loyal bettors.
Do you’ve a problem quitting or if your behaviour impacts your family. You can reach 1xBet’s customer service not solely by way of the contact type and reside chat but also through a free hotline . 1xBet also has a number of free bets promotions which might be unique to eSports betting in Canada. 1xBet is a bookmaker based mostly in Curaçao, where you’ll find a way to place sports activities bets since 2007. On the constructive facet of things, the 1XBet bet slip may be very quick, intuitive and easy to read. They additionally use staff logos of their featured events space and on the bet slip, which is a nice touch.
- Enter the sacred crypt and set off the free spins bonus for things to really get interesting.
- The web site is available in numerous languages, and the customer support group speaks a quantity of of them.
- However , if the quantity of games, larger odd playing bets, and the cost options enchant you, 1xBet Nigeria posseses an edge over other bookies in the industry.
- Of course, should you don’t discover the answer you were looking for, by all means, contact the employees.
- As such, xbet-zerkalo-sloty-1xbet-vhod18-site-iq6mi2dhd popularity was categorized as limited.
- On our coupon site yow will discover 1xBet specials and special offers 1xBet, in addition to 1000’s of presents from the world’s largest and finest online stores.
Although the positioning begins out strong with multiple choices in your signup bonus, it neglects to observe up, failing to offer attractive ongoing bonus opportunities. The website began as a sportsbook, so it’s unsurprising that its strongest and most relevant bonuses relate to that aspect of the casino. The site doesn’t demand that you submit additional identifying information at first. 1xbet Canada is most excited about getting its gamers to the gambling tables as rapidly as possible and betting money. It’s simple to search out the registration button on the primary menu at the high of the web page. When you click on on it, you have your choice of obtainable signup bonuses, then you’ll receive a username and password.
Also, digital sport betting has no summer season or winter pause between the seasons. The matches happen practically 24/7 with even one second of a pause throughout the whole 12 months. One instance of an business the place such reside bets work fairly good is soccer betting. If you redeem your code, say, at the beginning of the Champions’ League, you also can make some good money by the tip of the match. Moreover, the 1xBet promo code registration provides usually are not the only ones that are around during such events, so you can mix bonuses to profit from them altogether.
In the spirit of simplicity, when taking half in or offering funds, the on line casino will save your deposit funding information for you. Due to a variety of the casino’s authorized points up to now, our specialists have issues concerning 1xbet’s future viability. The firm that owns the platform, Bonnal Ltd., lost a legal contest with the Dutch government for promoting to its residents regardless of lacking permission to do so. Bonnal has rebranded within the past—it was previously known as Exinvest Ltd.
The company has already turn into one of many in type web sites in all of Eastern Europe, as properly as in loads of totally different places around the world. The procedures for a withdrawal or a deposit are comparatively brief on this web page. Plus – for them we now have a selection of greater than 20 fully totally different funds strategies. The finish of the first half brought the primary aim by the Zeta team. A Russian participant made a exact strike within the forty fifth minute, thereby gaining his team-mates’ lead.
To make deposits and withdrawals as painless as possible, 1xBet accepts quite a few fee methods. Whether you’re depositing or withdrawing at 1xBet, we’re assured that you’re going to discover their cost methods convenient and safe. Founded in 2007, 1xBet has quickly turn out to be a market chief for the East-European countries… Depending on the promotion, there aren’t any deposit bonuses or free bets, for instance.
You will encounter a easy navigational characteristic from the video games whatever the device you utilize like desktop, laptop, or a Smartphone, and so forth . Ladbrokes offer a large library of video games with reputed software program developers similar to Orbis and others being in again of the operator. Similarly, you have an choice to determine on a withdrawal method via a variety. The commission speed differs from setting to mode ranging from prompt to seven business days. It can be heartening as you can’t discover any service cost for any mode of withdrawal. While there’s not a processing cost for any with the modes of fee, the cost made by any method is immediately credited to the game enjoying account permitting you to play shortly.
If you are interested to find extra safe casinos like 1xbet Canada, then you possibly can go to our page that rates and ranks reliable Canadian casino sites. New Canadian clients register at 1xBET using their telephone number, email tackle or through one of six social media websites. We used email and our account number and password was despatched to us in seconds.There are many the reason why 1xBET is climbing the web betting business ranks. A by no means ending stream of sportsbook odds, Las Vegas fashion poker and on line casino enjoyable, plus their mix of priceless promotions, are all good ones. Never miss a minute mobile wagering, convenient deposit strategies, plus attentive client help, tie the package deal together.We’ve enjoyed our experiences and consider that you will as properly. 1xBet is in style amongst punters because it presents competitive odds in quite a few sports.
It changes day by day, definitely an excellent incentive to log on every single day to see what’s new. A pop-up window appears on the location if you click on the settings button at the top of the web page; right here you possibly can select what odds particulars you wish to see. The first possibility is to determine whether you desire to the European or Asian View.
After ending the registration course of, save your login and password information in a secure place for future entry to the 1xBet website mirror. In this blog publish, we’re going to present step-by-step directions on 1xBet registration, certainly one of many main on-line betting platforms on the planet. Learn additional about 1xBet, from setting up your account to putting your bets. You should stake a minimal of forty 4 ZMW and the odds must be no greater than 3.00. One of the explanations 1xBet is so well-liked is that they provide a registration bonus to new clients. You can get maintain of bonuses by making use of a promotional code for different actions – similar to registration, deposit replenishment, and one-time bonuses on 1xbet shares – amongst different issues.
In this text, we’ll examine the chances provided by two popular platforms, 1xbet and 22bet, that can help you decide which one is more appropriate for your betting wants. In the 1xbet vs 22bet comparison, both platforms supply competitive odds throughout a variety of sports and events. However, their strengths and focus differ, which may impression the chances depending on the particular sport and market. In the 22bet vs 1xbet debate, 1xbet is understood for offering greater odds for niche markets and less in style sports activities. This platform’s unique promotions and enhanced odds for particular occasions may be notably attractive to bettors looking for value bets.
Please, do not forget that to make the applying work simply in your system, it should run on Android 4.1 or later version. Dreams of Macau rapidly gained reputation amongst gamers upon its launch in mid-2020, because of its enticing features and potential for enormous wins as a lot as a most of 100,000x wager. It also incorporates its personal tackle the popular Megaways mechanic, which allows you to kind successful mixtures a quantity of ways on every spin. Like different releases from PG Soft, the sport contains several special features that add to the thrill, such as the free spins bonus spherical, a sticky wild modifier, and the cascading reels engine.
The trigger was the rise in a single other tax – on the conduct of enjoying and betting business. Taxes are one of the major sources of filling the price range of any state, along with Zambia. Android clients can place bets on nearly each factor through one single app that comes with a wealthy content, which precisely covers virtually the complete desktop website content material. You have to redeem a quantity of of them inside a sure time period or on a sure day. 1xBet will provide insurance and do you have to choose to buy that you simply pay .
With the assistance of our web site, you’ll study in regards to the simple registration or login to 1xbet.com. In the ever-evolving panorama of online playing, 1Xbet remains an emblem of trust, innovation, and accountable gaming. Its vibrant community and commitment to offering a first-class betting experience show the transformative power of people striving to make a optimistic impression on society. Motivated by their newfound objective, Benjamin, Jonathan, and Leo channeled their experiences and expertise into creating 1Xbet. They had been pushed by a passion for fairness, integrity, and responsible playing, aiming to supply customers across Germany with an unparalleled betting experience.
Then, simply in case that’s not enough transferring components for you, there’s additionally a big promotions panel that switches between offers we didn’t realise existed. First i attempted paytm quick and it shows payment denied by operator so i changed withdrawal method to upi. Third time i tried with phonepay and obtained message error inadequate stability. At this level, we’ve highlighted several areas by which this casino fails to measure up as an internet gaming platform. There are vital moral issues and reputation issues with this on line casino, but there are some constructive distinctions, including fee processing and sport choices. The on line casino additionally offers promotions for betting on ice hockey during the season; these sports activities promotions are essentially the most enticing , however they are limited to a single winner for the grand prize.
One of the most effective online bookmakers, 1xBet Exchange, enables you to bet on a variety of sports occasions with plenty of markets and really excessive odds. However, probably the most exciting a part of betting with a bookmaker is the trade betting part, the place you can transfer to the next level whereas nonetheless acting as a bookmaker. India, the second-most populous nation in the world, is full of sports enthusiasts, and the fervor with which Indians play cricket serves as an example to individuals all round the world. For cricket fans in India and the other 119 countries the place the IPL is currently broadcast, the 2008 IPL’s start unlocked a complete new universe of enjoyment. It was only a matter of time till this brand-new kind of leisure started to generate millions of dollars for cricket gamers throughout each IPL season.
If you manage to provide you with a decent betting technique, you may make great use of this selection. Mind that the company offers bonuses to new customers solely after they deposit some funds. The sum can be anything between $1 and $144 or any foreign money equal to this determine.
Still an emerging model within the English and Russian speaking territories, 1xbet can do better but is getting there. EWallets are the quickest way to go, with most withdrawals being immediate. If you wish to avoid any charges, you presumably can merely use your debit card. Those using credit and debit cards might be advised they have to wait 3-5 days. There are also unique 1xGames in the casino and your bonus can be utilized right here.
For anything, Twitter would be our advice because the team is fairly quick on there. Answers are concise and well-informed, together with about any 1xbet promo code queries. Though you can deposit from solely $1, do not overlook that your deposit bonus is a one hundred pc match using the proper 1xbet promo code.
The different apps – 1xPoker and 1xBrowser, as nicely as 1xPay – might be put in on older variations, although. It could moreover be hard to discover methods to use the 1xBet bonus successfully – it could flip into somewhat advanced. The bookmaker, although, attracts prospects from everywhere in the world with many other – higher than 30 in whole – promotions.
They want players around the globe to look for sites that provide accounts of their forex. They know it’s a draw as a result of so many currencies usually are not obtainable at big-name betting sites. In the tip although, keep in thoughts that they don’t seem to be going to pay out if you win greater than you lose.
There is also a greater than acceptable suite of on line casino and slot games, sports activities betting and live betting. Odds and pay-outs are honest here and the sport high quality is outstanding. The odds listed here are truthful and there’s a stay sports activities betting part too. You can wager on the sports activities part utilizing your bonus having entered the 1xbet promo code.
By checking this box, you comply with obtain personalized marketing content material. We are sending a verification code to the telephone quantity you supplied… If you want to register for the affiliate program you are capable of do that should you go to partners1xbet.com and click on ‘Registration’. It goes without saying that you should fill all the fields and once you are done simply anticipate the affirmation e mail. 1xBet Casino was based in 2007 and in the last couple of years managed to realize the higher hand of the local market. The on line casino may be very in style in Eastern Europe however lately, they’re discovering their way in different European nations in addition to Canada, and they are planning to expand their business in Asia as nicely.
The sportsbook has a massive selection of events to position bets on and includes every of the most important sports from across the globe. With soccer, football, tennis, tennis, and basketball, you might bet on a group or athlete to win the sport or match. You have to the choice to be a half of the pleasant betting expertise and place your bet on the group which you’ve chosen while the game goes about.
Users reveled within the pleasure and reliability that 1Xbet offered, solidifying its place as a number one gambling platform in Germany. 1XBet sports activities betting site has a wonderful way of ushering in its new members to the positioning. New gamers that get to open their accounts here stand to rise up to 100 1xbet apk 2022 percent as a welcome bonus on their initial deposit. This contains popular sports like hockey, ski leaping, water polo, basketball, soccer, and so much extra.
In addition, inside the 1xBet, there’s a on line casino video games on-line part, the place you presumably can monitor all occasions in actual time. To use all the capabilities of the Internet service, a client may have the ability to choose not solely a laptop computer but as nicely as any mobile gadget. Before we get into the nitty-gritty of 1xBet registration, let’s first have a look at what 1xBet is. 1xBet is an web betting platform that gives customers a selection of betting suppliers. These services embody sports betting, Esports games, on line casino video games, and additional.
It additionally makes its on-line betting website available across a quantity of devices, formats, and methods. Creating an account with 1xBet is a straightforward course of, taking just some minutes to complete. You’ll simply want handy over some of your private particulars and select a login and password. Once your account is ready, you presumably can leap into the betting action or go straight to the bonuses to see what may be obtainable.
The application doesn’t take up a lot space of the phone’s memory and has minor system requirements. Thanks to this, you might be able to put in the event even on low cost gadgets. Installation features of the most recent version of the apk and the iOS utility for the 1xBet bookmaker.
The provider promotes protected gambling and provides assets and tools to help users maintain management over their gaming behavior. This includes choices for self-exclusion, limiting deposits, and pausing while enjoying. 1xBet is conscious that gamers who want to have a smooth and trouble-free gaming expertise need convenient and reliable deposit strategies. That’s why 1xBet provides well-known and protected deposit options which are accepted in most counties. There are multiple choices out there to gamers, together with Debit Card, ePay, Dogecoin, MoneySafe, Wallet One, among others. Gamblers can reap the benefits of completely different bonuses and promotions to boost their gaming expertise.
Customers can also buy lottery tickets for well-known lotteries such because the UK Lotto and EuroMillions at 1xbet. Customers can enter lotteries from all over the world to extend their possibilities of profitable massive. It should come as no surprise that individuals who’re knowledgeable about the sport and the Indian Premier League make a lot of money every Cricket ID season! These folks will only have the ability to benefit from Cricket ID matches much extra easily if they’ve a Cricket ID from 1xbet.
We have been able to place a frankly ludicrous 50 bets earlier than the slip became full. The maximum stake allowed, nonetheless, is proscribed by no matter you’ve in your online account. We’re additionally impressed by the readability of the reside on line casino video games, in that each one is labelled with the wagering limit. For instance, there was a baccarat desk with a maximum bet of $3,000 available.
|
english
|
"""
-------------------------------------
# -*- coding: utf-8 -*-
# @Time : 2021/4/16 12:03:46
# @Author : Giyn
# @Email : <EMAIL>
# @File : mobility_model_construction.py
# @Software: PyCharm
-------------------------------------
"""
import numpy as np
from utils import ProgressBar
def markov_model(trajs: list, n_grid: int, _epsilon: float) -> np.ndarray:
"""
markov model
Args:
trajs : trajectory data
n_grid : number of secondary grids
_epsilon: privacy budget
Returns:
O_: intermediate point transition probability matrix
"""
O_ = np.zeros((n_grid, n_grid)) # establish n_grid * n_grid transition probability matrix
for t in trajs:
O_sub = np.zeros((n_grid, n_grid))
for i in range(len(t) - 1):
curr_point = t[i]
next_point = t[i + 1]
O_sub[curr_point][next_point] += 1
O_sub /= (len(t) - 1) # transition probability of the trajectory
O_ += O_sub
p = ProgressBar(n_grid, 'Generate midpoint transition probability matrix')
for i in range(n_grid):
p.update(i)
for j in range(n_grid):
noise = np.random.laplace(0, 1 / _epsilon) # add laplacian noise
O_[i][j] += noise
if O_[i][j] < 0:
O_[i][j] = 0
# compute X
row_sum = [sum(O_[i]) for i in range(n_grid)]
for j in range(n_grid):
O_[j] /= row_sum[j]
return O_
def mobility_model_main(n_grid: int, _epsilon: float, grid_trajs_path: str,
midpoint_movement_path: str):
"""
main function
Args:
n_grid : number of grids
_epsilon : privacy budget
grid_trajs_path : grid track file path
midpoint_movement_path: midpoint transition probability matrix file path
Returns:
"""
with open(grid_trajs_path, 'r') as grid_trajs_file:
T = [eval(traj) for traj in grid_trajs_file.readlines()]
with open(midpoint_movement_path, 'w') as midpoint_movement_file:
midpoint_movement_matrix = markov_model(T, n_grid, _epsilon)
for item in midpoint_movement_matrix:
each_line = ' '.join([str(i) for i in item]) + '\n'
midpoint_movement_file.writelines(each_line)
if __name__ == '__main__':
epsilon = 0.1
mobility_model_main(64, epsilon * 3 / 9,
f'../data/Geolife Trajectories 1.3/Middleware/grid_trajs_epsilon_{epsilon}.txt',
f'../data/Geolife Trajectories 1.3/Middleware/midpoint_movement_epsilon_{epsilon}.txt')
|
python
|
<filename>public/css/app.css<gh_stars>1-10
body {
text-align: center;
font-family: Arial, Helvetica, sans-serif;
}
h2 {
margin: 0 auto;
font-size: 35px;
margin: 10px;
}
.flex-container {
display: -webkit-box;
display: flex;
-webkit-box-pack: center;
justify-content: center;
-webkit-box-align: center;
align-items: center;
}
.flex-column {
height: 100%;
width: 100%;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
flex-direction: column;
}
.flex-wrap {
flex-wrap: wrap;
height: 432px;
width: 432px;
}
.square {
border: 2px solid rgba(0, 0, 0, 0.75);
height: 140px;
width: 140px;
}
#reset-button {
text-align: center;
font-size: 20px;
border: 1px solid black;
height: 55px;
width: 100px;
margin: 10px;
}
|
css
|
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2021 Aarno Labs, LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ------------------------------------------------------------------------------
"""Representation of a type in json."""
import xml.etree.ElementTree as ET
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
import chb.util.fileutil as UF
class UserBTypeStore:
def __init__(self, namedtypes: Dict[str, int]) -> None:
self._basetypes: Dict[str, "UserBType"] = {}
self._typedefs: Dict[str, "UserBType"] = {}
self._initialize(namedtypes)
def add_typedef(self, name: str, t: "UserBType") -> None:
self._typedefs[name] = t
def has_named_type(self, name) -> bool:
return name in self._basetypes or name in self._typedefs
def has_size_of(self, name) -> bool:
if name in self._basetypes:
return True
else:
return name in self._typedefs and self._typedefs[name].has_size()
def size_of(self, name: str) -> int:
if self.has_size_of(name):
if name in self._basetypes:
return self._basetypes[name].size
else:
return self._typedefs[name].size
else:
raise UF.CHBError("Size of named type: " + name + " not found")
def _initialize(self, namedtypes) -> None:
for (name, size) in namedtypes.items():
self._basetypes[name] = UserNamedBType(name, size=size)
class UserBType(ABC):
def __init__(self) -> None:
pass
@property
def is_named_type(self) -> bool:
return False
@property
def is_pointer_type(self) -> bool:
return False
@property
def is_array_type(self) -> bool:
return False
@property
def is_struct_type(self) -> bool:
return False
@property
@abstractmethod
def size(self) -> int:
...
def has_size(self) -> bool:
return False
def to_xml(self, node: ET.Element) -> None:
raise UF.CHBError("No implementation for to_xml: " + str(self))
def __str__(self) -> str:
return "btype"
class UserNamedBType(UserBType):
def __init__(self, name: str, size: Optional[int] = None) -> None:
self._name = name
self._size = size
@property
def name(self) -> str:
return self._name
def has_size(self) -> bool:
return self._size is not None
@property
def size(self) -> int:
if self._size is not None:
return self._size
else:
raise UF.CHBError("Size not available for " + self.name)
@property
def is_named_type(self) -> bool:
return True
def to_xml(self, node: ET.Element) -> None:
node.text = self.name
def __str__(self) -> str:
return self.name
class UserPointerBType(UserBType):
def __init__(self, tgt: UserBType) -> None:
self._tgt = tgt
@property
def target_type(self) -> UserBType:
return self._tgt
@property
def is_pointer_type(self) -> bool:
return True
def has_size(self) -> bool:
return True
@property
def size(self) -> int:
return 4
def to_xml(self, node: ET.Element) -> None:
ptrnode = ET.Element("ptr")
node.append(ptrnode)
self.target_type.to_xml(ptrnode)
def __str__(self) -> str:
return "*" + str(self.target_type)
class UserArrayBType(UserBType):
def __init__(self, tgt: UserBType, num_elements) -> None:
self._tgt = tgt
self._num_elements = num_elements
@property
def element_type(self) -> UserBType:
return self._tgt
@property
def num_elements(self) -> int:
return self._num_elements
@property
def is_array_type(self) -> bool:
return True
def has_size(self) -> bool:
return self.element_type.has_size()
@property
def size(self) -> int:
return self.element_type.size * self.num_elements
def to_xml(self, node: ET.Element) -> None:
anode = ET.Element("array")
node.append(anode)
self.element_type.to_xml(anode)
anode.set("size", str(self.num_elements))
def __str__(self) -> str:
return str(self.element_type) + "[" + str(self.num_elements) + "]"
class UserStructBType(UserBType):
def __init__(self, fields: List["UserStructBFieldInfo"]) -> None:
self._fields = fields
@property
def fields(self) -> List["UserStructBFieldInfo"]:
return self._fields
@property
def is_struct_type(self) -> bool:
return True
def has_size(self) -> bool:
return True
@property
def size(self) -> int:
return self.fields[-1].offset + self.fields[-1].size
def to_xml(self, node: ET.Element) -> None:
ffnode = ET.Element("fields")
node.append(ffnode)
for fld in self.fields:
fnode = ET.Element("field")
ffnode.append(fnode)
fld.to_xml(fnode)
def __str__(self) -> str:
lines: List[str] = []
for f in self.fields:
lines.append(str(f))
return "\n".join(lines)
class UserStructBFieldInfo:
def __init__(
self,
name: str,
btype: UserBType,
offset: int,
size: int) -> None:
self._name = name
self._btype = btype
self._offset = offset
self._size = size
@property
def name(self) -> str:
return self._name
@property
def field_type(self) -> "UserBType":
return self._btype
@property
def offset(self) -> int:
return self._offset
@property
def size(self) -> int:
return self._size
def to_xml(self, node: ET.Element) -> None:
node.set("name", self.name)
node.set("size", str(self.size))
node.set("offset", str(self.offset))
tnode = ET.Element("type")
node.append(tnode)
self.field_type.to_xml(tnode)
def __str__(self) -> str:
return str(self.offset).rjust(3) + " " + self.name + ": " + str(self.field_type)
|
python
|
<reponame>rolocampusano/nber
{
"id": 24926,
"citation_title": "Mergers and Marginal Costs: New Evidence on Hospital Buyer Power",
"citation_author": [
"<NAME>",
"<NAME>",
"<NAME>"
],
"citation_publication_date": "2018-08-20",
"issue_date": "2018-08-17",
"revision_date": "2018-10-12",
"topics": [
"Health, Education, and Welfare",
"Health",
"Industrial Organization",
"Antitrust"
],
"program": [
"Health Care",
"Industrial Organization"
],
"projects": null,
"working_groups": null,
"abstract": "\n\nWe estimate the effects of horizontal mergers on marginal cost efficiencies \u2013 an ubiquitous merger justification \u2013 using data containing supply purchase orders from a large sample of US hospitals 2009-2015. The data provide a level of detail that has been difficult to observe previously, and a variety of product categories that allows us to examine economic mechanisms underlying \u201cbuyer power.\u201d We find that merger target hospitals save on average $176 thousand (or 1.5 percent) annually, driven by geographically local efficiencies in price negotiations for high-tech \u201cphysician preference items.\u201d We find only mixed evidence on savings by acquirers.\n\n",
"acknowledgement": "\nThe data used in this paper were generously provided, in part, by the ECRI Institute (www.ecri.org). We gratefully acknowledge financial support from the Wharton Dean\u2019s Research Fund and Public Policy Initiative, the Wolpow Family, and NSF Grant 30067535. We thank <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for assistance in constructing the merger panel. Harrison Byers, <NAME>, and <NAME> provided excellent research assistance. Any errors are our own. The views expressed herein are those of the authors and do not necessarily reflect the views of the National Bureau of Economic Research.\n\n\n"
}
|
json
|
<filename>assets/buildings/pgi/pgi-processed-food.json<gh_stars>0
[
{
"id": "pgi.food.proc",
"imageId": "pgi.food.proc",
"constructionImageId": "generic.construction.5",
"name": {
"DE": "<NAME>",
"EN": "Large Food Processor",
"ES": "Gran procesador de alimentos",
"FR": "Grand robot culinaire",
"IT": "Grande robot da cucina",
"PT": "Grande processador de alimentos"
},
"sealId": "PGI",
"zoneId": "INDUSTRIAL",
"industryCategoryId": "INDUSTRY",
"industryTypeId": "PROCESSED_FOOD",
"requiredInventionIds": [
"LSFoodPrc"
]
},
{
"id": "pgi.food.proc.small",
"imageId": "pgi.food.proc.small",
"constructionImageId": "generic.construction.3",
"name": {
"DE": "Küchenmaschine",
"EN": "Food Processor",
"ES": "Procesador de alimentos",
"FR": "Robot culinaire",
"IT": "Robot da cucina",
"PT": "Processador de alimentos"
},
"sealId": "PGI",
"zoneId": "INDUSTRIAL",
"industryCategoryId": "INDUSTRY",
"industryTypeId": "PROCESSED_FOOD",
"requiredInventionIds": [
"FoodPrcLic"
]
}
]
|
json
|
Income Tax officials today conducted raids here in the house of sand-mining baron Shekar Reddy’s associate Ratnam, a quarry contractor who was arrested a couple of days ago on charge of exchanging unaccounted old currency notes.
A team of I-T officials from Perambalur, about 150 km from here, were conducting searches at the house of Ratnam from around 6 am, official sources said. The searches are going on, they said declining to give any further detail.
CBI had on December 22 arrested Ratnam and another quarry contractor Ramachandran, and Reddy’s auditor Premkumar following investigations in connection with recent Income Tax searches at his residence and office in Chennai that resulted in seizure of 127 kg of gold and over Rs 170 crore in cash post-demonetisation.
Reddy, along with his associate Srinivasulu, was arrested by CBI on December 21. The five have been accused of converting the unaccounted cash held by them in old currency notes to new notes with the help of unknown public servants from different banks within 24 days from the date demonetisation was announced (November 8).
|
english
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sige.modelo.sessionbean;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import sige.modelo.entidade.Grupo;
@Stateless
public class GrupoSBean {
@PersistenceContext(unitName = "sigePU")
EntityManager em;
public void salvar(Grupo grupo) {
em.merge(grupo);
}
public void excluir(Grupo grupo) {
em.remove(em.find(Grupo.class, grupo.getId()));
}
public Grupo pesquisar(Long id) {
return em.find(Grupo.class, id);
}
public List<Grupo> pesquisar(String nome) {
List<Grupo> listaGrupo;
Query consulta = em.createNamedQuery("Grupo.findByNome");
consulta.setParameter("nome", nome.toUpperCase() + "%");
listaGrupo = consulta.getResultList();
return listaGrupo;
}
}
|
java
|
'use strict'
module.exports = root
var lineFeed = '\n'
// Stringify a root.
// Adds a final newline to ensure valid POSIX files. */
function root(node) {
return this.block(node) + lineFeed
}
|
javascript
|
<filename>corpus/class/eclipse.jdt.ui/1527.java
package p;
public class A {
private static String NAME = "N";
private static String getNAME() {
return NAME;
}
}
|
java
|
The manager of the Indian Overseas Bank branch in Keelkattalai, which saw a daring robbery on Monday, was warned barely four days ago to install CCTV and engage security guards, sources in the Chennai Police said.
Soon after the robbery in the Bank of Baroda (branch on the Rajiv Gandhi Salai on January 23, senior police officers held meetings with representatives of various banks to sensitise them to the urgent need to install CCTVs and engage trained private security personnel.
“The officials in the IOB Branch in Keelkattalai were also alerted less than a week ago by the Madipakkam police…they claimed to have written to their higher authorities seeking sanction,” an investigator told The Hindu .
Since the looted money was from the teller's cash counter, there was no record of serial numbers on the currency notes. As in the earlier robbery case, the robbers locked up all the bank employees and customers in one room and took away their mobile phones. The cashiers who had gone out for lunch returned and opened the room, police sources said.
While forensic experts were looking for fingerprints and other evidence at the scene of crime, special teams formed to investigate the case mounted surveillance at railway stations and major bus stands.
Since both banks that were looted within a month had no CCTV or effective security system, police suspect that the gang might have conducted a dry run before striking.
“We have a suspicion that they might have visited other banks to check if it was feasible to plan a robbery there. Steps have been taken to gather the video footage recorded on the CCTV network of certain banks located in vulnerable areas,” a police official said.
Confirming that police had alerted the IOB branch in Keelkattalai to install CCTV as a security measure just four days ago, Commissioner of Police J. K. Tripathy said investigators were looking into all angles and efforts were on to peruse video footage records in some bank branches and ATMs.
|
english
|
The government on Thursday said it has approved three Foreign Direct Investment (FDI) proposals amounting to Rs.135.84 crore, based on Foreign Investment Promotion Board (FIPB) recommendations.
The approved proposals were from Scalene Works People Solutions LLP, GVK Biosciences Pvt Ltd and GMS Pharma (Singapore) Pvt Ltd.
Nine proposals – from HDFC Standard Life Insurance, Tata Sikorsky Aerospace, Jupiter Satellite India, Financial Times (India) Pvt Ltd, Volvo Asset Finance lndia, Aviva Life lnsurance, Indus Way Emerging Market Fund Series ll and Firefly Networks – were deferred, while CAN Cable Pvt Ltd’s proposal was the lone one rejected.
|
english
|
<gh_stars>0
import React, { Fragment } from 'react';
import { Modal, Upload, Icon } from 'antd';
import AvatarEditor from 'react-avatar-editor';
const gEditorStyle = { display: 'block', margin: '10px auto' };
export function dataURLtoBlob(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime,
});
}
export default class ImageCropper extends React.Component {
state = {
imageFile: null,
scale: 1,
width: 400,
height: 200,
borderRadius: 0,
};
componentDidMount() {
const { scale, width, height, borderRadius } = this.props;
this.setState(state => ({
...state,
scale: scale || 1,
width: width || 400,
height: height || 200,
borderRadius: borderRadius || 0,
}));
const self = this;
const scrollFunc = function(e) {
// var direct = 0;
e = e || window.event;
if (e.wheelDelta) {
//判断浏览器IE,谷歌滑轮事件
if (e.wheelDelta > 0) {
//当滑轮向上滚动时
self.setState({ scale: self.state.scale + 0.1 });
}
if (e.wheelDelta < 0) {
//当滑轮向下滚动时
self.setState({ scale: self.state.scale - 0.1 });
}
} else if (e.detail) {
//Firefox滑轮事件
if (e.detail > 0) {
//当滑轮向上滚动时
self.setState({ scale: self.state.scale + 0.1 });
}
if (e.detail < 0) {
//当滑轮向下滚动时
self.setState({ scale: self.state.scale - 0.1 });
}
}
};
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
} // W3C
window.onmousewheel = document.onmousewheel = scrollFunc; // IE/Opera/Chrome
}
beforeUpload = imageFile => {
this.setState({ imageFile });
return false;
};
toUpload = () => {
const { onUpload } = this.props;
const { imageFile } = this.state;
if (!!onUpload && !!imageFile && !!this.editor) {
const fakefile = dataURLtoBlob(this.editor.getImageScaledToCanvas().toDataURL('image/png'));
fakefile.name = imageFile.name;
onUpload(fakefile);
}
this.setState({ imageFile: null });
};
toCloseModal = () => {
const { onCancel } = this.props;
if (!!onCancel) onCancel();
this.setState({ imageFile: null });
};
onScaleChange = value => {
this.setState(state => ({
...state,
scale: value,
}));
};
onWidthChange = value => {
this.setState(state => ({
...state,
width: value,
}));
};
onHeightChange = value => {
this.setState(state => ({
...state,
height: value,
}));
};
onRadiusChange = value => {
this.setState(state => ({
...state,
borderRadius: value,
}));
};
render() {
const { imageFile, scale, width, height, borderRadius } = this.state;
const { url } = this.props;
return (
<Fragment>
<Upload
action={null}
accept="image/*"
showUploadList={false}
beforeUpload={this.beforeUpload}
>
<div
style={{
textAlign: 'center',
width,
height,
border: '1px #ccc dashed',
position: 'relative',
cursor: 'pointer',
}}
>
{!url ? (
<Fragment>
<p className="ant-upload-drag-icon" style={{ width, paddingTop: height * 0.3 }}>
<Icon type="upload" />
</p>
<p className="ant-upload-text">点击上传图片</p>
</Fragment>
) : (
<img style={{ maxWidth: width }} src={url} />
)}
</div>
</Upload>
<Modal
visible={!!imageFile}
title="图片裁剪"
okText="确认"
cancelText="取消"
width={width < 200 ? 400 : width + 100}
height={height}
onOk={this.toUpload}
onCancel={this.toCloseModal}
>
<AvatarEditor
border={1}
color={[72, 118, 255, 0.6]}
style={gEditorStyle}
ref={e => (this.editor = e)}
image={imageFile}
scale={scale}
width={width}
height={height}
borderRadius={borderRadius}
/>
<br />
<h3>{`请上传 ${width}px(宽) * ${height}px(高) 大小的图片`}</h3>
</Modal>
</Fragment>
);
}
}
|
javascript
|
<gh_stars>1-10
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "asm/macroAssembler.hpp"
#include "code/vtableStubs.hpp"
#include "interp_masm_x86.hpp"
#include "memory/resourceArea.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/klassVtable.hpp"
#include "runtime/sharedRuntime.hpp"
#include "vmreg_x86.inline.hpp"
#ifdef COMPILER2
#include "opto/runtime.hpp"
#endif
// machine-dependent part of VtableStubs: create VtableStub of correct size and
// initialize its code
#define __ masm->
#ifndef PRODUCT
extern "C" void bad_compiled_vtable_index(JavaThread* thread, oop receiver, int index);
#endif
// These stubs are used by the compiler only.
// Argument registers, which must be preserved:
// rcx - receiver (always first argument)
// rdx - second argument (if any)
// Other registers that might be usable:
// rax - inline cache register (is interface for itable stub)
// rbx - method (used when calling out to interpreter)
// Available now, but may become callee-save at some point:
// rsi, rdi
// Note that rax and rdx are also used for return values.
//
VtableStub* VtableStubs::create_vtable_stub(int vtable_index) {
const int i486_code_length = VtableStub::pd_code_size_limit(true);
VtableStub* s = new(i486_code_length) VtableStub(true, vtable_index);
// Can be NULL if there is no free space in the code cache.
if (s == NULL) {
return NULL;
}
ResourceMark rm;
CodeBuffer cb(s->entry_point(), i486_code_length);
MacroAssembler* masm = new MacroAssembler(&cb);
#ifndef PRODUCT
if (CountCompiledCalls) {
__ incrementl(ExternalAddress((address) SharedRuntime::nof_megamorphic_calls_addr()));
}
#endif /* PRODUCT */
// get receiver (need to skip return address on top of stack)
assert(VtableStub::receiver_location() == rcx->as_VMReg(), "receiver expected in rcx");
// get receiver klass
address npe_addr = __ pc();
__ movptr(rax, Address(rcx, oopDesc::klass_offset_in_bytes()));
#ifndef PRODUCT
if (DebugVtables) {
Label L;
// check offset vs vtable length
__ cmpl(Address(rax, InstanceKlass::vtable_length_offset()*wordSize), vtable_index*vtableEntry::size());
__ jcc(Assembler::greater, L);
__ movl(rbx, vtable_index);
__ call_VM(noreg, CAST_FROM_FN_PTR(address, bad_compiled_vtable_index), rcx, rbx);
__ bind(L);
}
#endif // PRODUCT
const Register method = rbx;
// load Method* and target address
__ lookup_virtual_method(rax, vtable_index, method);
if (DebugVtables) {
Label L;
__ cmpptr(method, (int32_t)NULL_WORD);
__ jcc(Assembler::equal, L);
__ cmpptr(Address(method, Method::from_compiled_offset()), (int32_t)NULL_WORD);
__ jcc(Assembler::notZero, L);
__ stop("Vtable entry is NULL");
__ bind(L);
}
// rax,: receiver klass
// method (rbx): Method*
// rcx: receiver
address ame_addr = __ pc();
__ jmp( Address(method, Method::from_compiled_offset()));
masm->flush();
if (PrintMiscellaneous && (WizardMode || Verbose)) {
tty->print_cr("vtable #%d at "PTR_FORMAT"[%d] left over: %d",
vtable_index, s->entry_point(),
(int)(s->code_end() - s->entry_point()),
(int)(s->code_end() - __ pc()));
}
guarantee(__ pc() <= s->code_end(), "overflowed buffer");
// shut the door on sizing bugs
int slop = 3; // 32-bit offset is this much larger than an 8-bit one
assert(vtable_index > 10 || __ pc() + slop <= s->code_end(), "room for 32-bit offset");
s->set_exception_points(npe_addr, ame_addr);
return s;
}
VtableStub* VtableStubs::create_itable_stub(int itable_index) {
// Note well: pd_code_size_limit is the absolute minimum we can get away with. If you
// add code here, bump the code stub size returned by pd_code_size_limit!
const int i486_code_length = VtableStub::pd_code_size_limit(false);
VtableStub* s = new(i486_code_length) VtableStub(false, itable_index);
// Can be NULL if there is no free space in the code cache.
if (s == NULL) {
return NULL;
}
ResourceMark rm;
CodeBuffer cb(s->entry_point(), i486_code_length);
MacroAssembler* masm = new MacroAssembler(&cb);
// Entry arguments:
// rax,: Interface
// rcx: Receiver
#ifndef PRODUCT
if (CountCompiledCalls) {
__ incrementl(ExternalAddress((address) SharedRuntime::nof_megamorphic_calls_addr()));
}
#endif /* PRODUCT */
// get receiver (need to skip return address on top of stack)
assert(VtableStub::receiver_location() == rcx->as_VMReg(), "receiver expected in rcx");
// get receiver klass (also an implicit null-check)
address npe_addr = __ pc();
__ movptr(rsi, Address(rcx, oopDesc::klass_offset_in_bytes()));
// Most registers are in use; we'll use rax, rbx, rsi, rdi
// (If we need to make rsi, rdi callee-save, do a push/pop here.)
const Register method = rbx;
Label throw_icce;
// Get Method* and entrypoint for compiler
__ lookup_interface_method(// inputs: rec. class, interface, itable index
rsi, rax, itable_index,
// outputs: method, scan temp. reg
method, rdi,
throw_icce);
// method (rbx): Method*
// rcx: receiver
#ifdef ASSERT
if (DebugVtables) {
Label L1;
__ cmpptr(method, (int32_t)NULL_WORD);
__ jcc(Assembler::equal, L1);
__ cmpptr(Address(method, Method::from_compiled_offset()), (int32_t)NULL_WORD);
__ jcc(Assembler::notZero, L1);
__ stop("Method* is null");
__ bind(L1);
}
#endif // ASSERT
address ame_addr = __ pc();
__ jmp(Address(method, Method::from_compiled_offset()));
__ bind(throw_icce);
__ jump(RuntimeAddress(StubRoutines::throw_IncompatibleClassChangeError_entry()));
masm->flush();
if (PrintMiscellaneous && (WizardMode || Verbose)) {
tty->print_cr("itable #%d at "PTR_FORMAT"[%d] left over: %d",
itable_index, s->entry_point(),
(int)(s->code_end() - s->entry_point()),
(int)(s->code_end() - __ pc()));
}
guarantee(__ pc() <= s->code_end(), "overflowed buffer");
// shut the door on sizing bugs
int slop = 3; // 32-bit offset is this much larger than an 8-bit one
assert(itable_index > 10 || __ pc() + slop <= s->code_end(), "room for 32-bit offset");
s->set_exception_points(npe_addr, ame_addr);
return s;
}
int VtableStub::pd_code_size_limit(bool is_vtable_stub) {
if (is_vtable_stub) {
// Vtable stub size
return (DebugVtables ? 210 : 16) + (CountCompiledCalls ? 6 : 0);
} else {
// Itable stub size
return (DebugVtables ? 256 : 66) + (CountCompiledCalls ? 6 : 0);
}
// In order to tune these parameters, run the JVM with VM options
// +PrintMiscellaneous and +WizardMode to see information about
// actual itable stubs. Look for lines like this:
// itable #1 at 0x5551212[65] left over: 3
// Reduce the constants so that the "left over" number is >=3
// for the common cases.
// Do not aim at a left-over number of zero, because a
// large vtable or itable index (> 16) will require a 32-bit
// immediate displacement instead of an 8-bit one.
//
// The JVM98 app. _202_jess has a megamorphic interface call.
// The itable code looks like this:
// Decoding VtableStub itbl[1]@1
// mov 0x4(%ecx),%esi
// mov 0xe8(%esi),%edi
// lea 0x130(%esi,%edi,4),%edi
// add $0x7,%edi
// and $0xfffffff8,%edi
// lea 0x4(%esi),%esi
// mov (%edi),%ebx
// cmp %ebx,%eax
// je success
// loop:
// test %ebx,%ebx
// je throw_icce
// add $0x8,%edi
// mov (%edi),%ebx
// cmp %ebx,%eax
// jne loop
// success:
// mov 0x4(%edi),%edi
// mov (%esi,%edi,1),%ebx
// jmp *0x44(%ebx)
// throw_icce:
// jmp throw_ICCE_entry
}
int VtableStub::pd_code_alignment() {
return wordSize;
}
|
cpp
|
{
"listing_id": 141550,
"id": 2685074,
"date": "2012-10-22",
"reviewer_id": 178518,
"reviewer_name": "Iris",
"text": "Fiona's place was great, really cute and creative, just as advertised. She was also really friendly and great to book with, though we didn't get to meet her personally since she was out of town. I loved the house and the neighborhood - it's been one of my favorite Airbnb experiences. We were tired of the SoCo experience in Austin, and I much prefer the area the cottage is in. The tacqueria down and across the street is good for a cheap, hot breakfast, plus you're near all the great spots in Austin. We paddleboarded on the lake, caught a concert, ate good food and just generally hung out and had a great time. Definitely want to come back.",
"title": "Sweet, Sexy Studio in the '02",
"host_id": 688306,
"listing_latitude": 30.25581961280061,
"listing_longitude": -97.72709090146905,
"host_name": "Fiona"
}
|
json
|
{
"dataSourceId": 2,
"objectTypeId": 1,
"caption": "Новое название иисточника данных",
"measureItem": "Новая единица измерениия",
"dataSourceGroupId": 5000
}
|
json
|
{"article": "As Apple fans paid attention to every detail, Twitter user, <NAME>, joked that the Apple watch was set at 10:09 in all images because 10:10 was \"just too mainstream.\" He actually may have been _ . You may not have _ but the default setting in advertisements for many new watches is 10:10. Many well-known brands, _ Rolex and <NAME>, set their watches to this time for their advertisements. Could Apple have set their watch at 10:09 to _ they are ahead of the others? Perhaps, _ a quick look at other watch advertisements suggests Apple is not the first to turn away from the 10 past 10 time. That's because many companies show their watches at this time _ for artistic reasons. It makes _ therefore to adjust it by just a few minutes _ this standard time according to what particular brands think _ their watch best. However, it is thought that around 10 past 10 shows the watch at the best _ . If the logo is _ underneath the 12, this time also has the advantage of \"framing\" the brand name between the two hands. It's also a symmetrical time, making it _ to the eye. Often manufacturers photograph the watch with the second hand in a position _ emphasises this proportionality . Another favorite time with clock vendors has been 20 past 8, because of its symmetry. However, 10 past 10 is _ to be a more \"positive\" time by brand experts, as it looks as if the _ of the watch is smiling. It's likely that Apple decided to set its time at 10:09 to _ itself within watch-making tradition. It may just be a minute in time, but 10:09 is further _ that Apple is taking its new watch very seriously, This is not being _ to as a \"smart watch\"; this is a watch that both wearable tech and the watch industry should take _ .", "options": [["smart", "right", "honest", "lucky"], ["believed", "discovered", "noticed", "known"], ["inviting", "approving", "connecting", "including"], ["pretend", "predict", "suggest", "announce"], ["but", "because", "and", "so"], ["hardly", "probably", "surely", "purely"], ["sense", "mistakes", "efforts", "trouble"], ["around", "from", "through", "behind"], ["concerns", "suits", "adapts", "prepares"], ["color", "place", "time", "angle"], ["carefully", "directly", "confidently", "correctly"], ["confusing", "surprising", "pleasing", "annoying"], ["which", "what", "when", "where"], ["defined", "supposed", "determined", "thought"], ["time", "frame", "face", "heart"], ["plan", "establish", "create", "finish"], ["instruction", "understanding", "explanation", "evidence"], ["referred", "remembered", "asked", "required"], ["hopefully", "seriously", "successfully", "Strictly"]], "answers": ["B", "C", "D", "C", "A", "D", "A", "A", "B", "D", "B", "C", "A", "D", "C", "B", "D", "A", "B"]}
|
json
|
# -*- coding: utf-8 -*-
#
# Copyright 2019 SoloKeys Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distributed except according to those terms.
from numbers import Number
from threading import Event, Timer
def to_websafe(data):
data = data.replace("+", "-")
data = data.replace("/", "_")
data = data.replace("=", "")
return data
def from_websafe(data):
data = data.replace("-", "+")
data = data.replace("_", "/")
return data + "=="[: (3 * len(data)) % 4]
class Timeout(object):
"""Utility class for adding a timeout to an event.
:param time_or_event: A number, in seconds, or a threading.Event object.
:ivar event: The Event associated with the Timeout.
:ivar timer: The Timer associated with the Timeout, if any.
"""
def __init__(self, time_or_event):
if isinstance(time_or_event, Number):
self.event = Event()
self.timer = Timer(time_or_event, self.event.set)
else:
self.event = time_or_event
self.timer = None
def __enter__(self):
if self.timer:
self.timer.start()
return self.event
def __exit__(self, exc_type, exc_val, exc_tb):
if self.timer:
self.timer.cancel()
self.timer.join()
|
python
|
{
"actions": {
"install": "Install This Mod",
"installBepInEx": "BepInExPack Needs To Be Installed Before Any Mods Can.",
"selectInstallLocation": "Select Your Risk of Rain 2 Install Location.",
"view": "View On Thunderstore"
},
"buttons": {
"change": "Change",
"close": "Close",
"delete": "Delete",
"export": "Export",
"import": "Import",
"install": "Install",
"installBepInEx": "Install BepInExPack",
"moreInfo": "More Info",
"refreshList": "Refresh List",
"selectFolder": "Select Folder",
"settings": "Settings",
"uninstall": "Uninstall",
"updateBepInEx": "Update BepInExPack"
},
"descriptions": {
"author": "Author",
"availableVersions": "Available Versions",
"description": "Description",
"latestVersion": "Latest Version",
"name": "Name"
},
"panels": {
"description": "Description",
"installed": "Installed",
"notInstalled": "Not Installed"
},
"settings": {
"autoUpdate": "Automatically Update Installed Mods",
"changeGameLocation": "Change Risk of Rain 2 Install Location",
"deleteMods": "Delete All Installed Mods",
"disableMods": "Disable All Installed Mods",
"export": "Export Installed Mods",
"import": "Import a Mod Configuration"
},
"statuses": {
"endFetch": "Finished fetching mods.",
"startFetch": "Fetching mods from Thunderstore.io..."
},
"title": "RoR2 Mod Manager",
"warnings": {
"deprecated": "This mod has been deprecated!",
"note": "NOTE"
}
}
|
json
|
- Lifestyle Beach Day Fashion: Tips and Tricks for a Stylish Look!
Microsoft Excel is probably one of the handiest and extensively used tools today. With calculations, graph tools, tables, and many others - Microsoft Excel is an easy software for all your professional and personal work. However, having a couple of keyboard shortcuts for Microsoft Excel could make it much easier to operate.
Whether you're a pro getting a hang of the keyboard shortcuts could help save time and boost productivity. And if you're a beginner, learning the keyboard shortcuts will help you navigate through MS Excel much easily. We've listed out 15 simple and easy-to-remember shortcut keys for Microsoft Excel.
F4: Repeats the previous command, including repeating the last action.
F9: One of the most important shortcut keys, this enables you to calculate all worksheets in all open workbooks.
F11: Enables you to make a bar graph on the selected data in a separate sheet.
F12: Pops open the Save As window, allowing you to save the MS Excel file in any location you wish.
Shift + F11: This allows you to insert a new worksheet within the same MS Excel workbook.
Shift + F9: Shortcut enables calculations only in the active worksheets.
Shift + Arrow key: Adds a new cell in the direction of the Arrow key used.
Ctrl + F1: The shortcut helps to show or hide the ribbon.
Ctrl + F2: Switches to print preview.
Ctrl + Shift + U: Expands or collapses the formula bar.
Ctrl + Shift + $: Selected cells formatted as currency.
Ctrl + Shift + #: Selected cells formatted as date with day, month, year format.
Ctrl + Shift + %: Selected cells formatted as percentage.
Alt + F1: This allows you to make an embedded bar chart on the selected cells.
Alt + Q: Shortcut key opens the 'Tell me what you want to do', enabling you to search for a feature.
Apart from these, there are a couple of basic shortcut keys that can be used across Microsoft Office. Some are listed below:
Ctrl + S: Saves the file'
|
english
|
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="apple-touch-icon.png" type="image/x-icon">
<title>Social</title>
</head>
<body>
<h1>Minhas redes sociais</h1>
<h2>Quem sou eu?</h2>
<img src="image.jpg" alt="">
<p>Meu nome é <strong><NAME></strong>, sou estudante de programação e pretendo seguir carreira de programador Back-End.</p>
<h2>Como falar comigo?</h2>
<ul type="square">
<li><img src="icone-github.png" alt=""><a href="https://github.com/IsaiasRibeiro" target="_blank" rel = "external">/IsaiasRibeiro </a> - Acesse meu repositório público no GitHub</li>
<li><img src="icone-facebook.png" alt=""><a href="https://www.facebook.com/isaias.ribeiro.31"target="_blank" rel = "external">/IsaiasRibeiro</a> - Me acompanhe lá no Facebook</li>
<li><img src="icone-instagram.png" alt=""><a href="https://www.instagram.com/isaias._ribeiro/?hl=pt-br"target="_blank" rel = "external">/IsaiasRibeiro</a> - Me segue lá no Instagram</li>
</ul>
</body>
</html>
|
html
|
Having been away from WWE since September 2022, popular RAW Superstar Tommaso Ciampa has released a video showcasing how his injury rehab is going.
Following his United States Championship match against Bobby Lashley on September 17th last year, the former NXT Champion suffered an unfortunate hip injury. He was also associated with The Miz following his move to the main roster.
Earlier today, the RAW Superstar posted a video on his Instagram profile, as he was seen exercising his surgically repaired hip.
"Injuries suck. More often than not, injuries are out of our control. But how we choose to respond to adversity is 100% in our control," wrote the former NXT Champion.
Ciampa has been in World Wrestling Entertainment for almost ten years. While he has only just arrived on the main roster, he has been part of various iconic storylines in the company's third brand, NXT.
During the Boston native's first run on RAW last year, he was surprisingly paired with The Miz, who looked to ease Ciampa's transition to the main roster.
During a recent interview with the New York Post, The Miz was asked to give his opinion on Tommaso Ciampa's time on RAW so far.
Despite their contrasting appearances and journeys in the wrestling business, the paring of Ciampa and The Miz last summer on RAW made for some highly entertaining TV.
How far can Tommaso Ciampa go in WWE? Give us your thoughts in the comments section below.
|
english
|
{
"name": "grapesjs-style-bg",
"version": "1.0.5",
"description": "Full-stack background style property type for GrapesJS, with the possibility to add images, colors, and gradients",
"main": "dist/grapesjs-style-bg.min.js",
"repository": {
"type": "git",
"url": "https://github.com/artf/grapesjs-style-bg.git"
},
"scripts": {
"start": "grapesjs-cli serve",
"build": "grapesjs-cli build"
},
"keywords": [
"grapesjs",
"plugin"
],
"devDependencies": {
"grapesjs-cli": "^1.0.14"
},
"license": "MIT",
"dependencies": {
"grapesjs-style-gradient": "^2.0.14"
}
}
|
json
|
Ukrainiana writes about a house being built on the mass burial site for victims of a 19th-century anthrax epidemics in Kyiv.
Our Man in Gdansk suspects there's a difference between Kyiv hotels and those outside Ukraine's capital.
There's something to grieve and much to celebrate when the Baltic states join the Schengen, writes Marginalia.
TOL's Belarus writes about the possible reasons behind Russia's $1. 5-billion loan to Belarus.
Ukrainiana translates a video in which Victor Yanukovych is threatening to sue a journalist for questions on murky privatization deal.
Yulia Tymoshenko returned as Ukraine's prime minister on Dec. 18. Five days later, she was in Donetsk region, visiting the site of Ukraine's worst coal mining accident, the troubled Zasyadko mine. While there, she declared: "We'll be working on it and will make it so that in our country both young people and children would want to become coal miners. " Below is a discussion of Tymoshenko's promise that took place at Korrespondent. net, a Ukrainian news site.
Orange Ukraine writes about the brief arrest of two Ukrainian journalists at the Charles de Gaulle airport in Paris – for what seems like an exhausted transit passengers’ prank.
Orange Ukraine writes about priorities of Yulia Tymoshenko's cabinet and about the transfer of power from the old government to the new.
De Rebus Antiquis Et Novis writes about the history of Cheka and the Red Terror.
De Rebus Antiquis Et Novis writes about a little-known 1963 rally in Moscow's Red Square, when 500 African students rallied against racial discrimination, following the death of a Ghanian fellow student.
Orange Ukraine reposts a newspaper piece on parliamentary immunity – and impunity.
Ukraine: God or Demons Against Tymoshenko?
Ukrainian Musical Matters writes about a 1916 Ukrainian song that became a Christmas hit in the United States.
Orange Ukraine has a roundup of all things that are wrong with the Ukrainian politics.
|
english
|
# Copyright (c) 2001-2022 Aspose Pty Ltd. All Rights Reserved.
#
# This file is part of Aspose.Words. The source code in this file
# is only intended as a supplement to the documentation, and is provided
# "as is", without warranty of any kind, either expressed or implied.
import uuid
from datetime import datetime
import aspose.words as aw
import aspose.pydrawing as drawing
from api_example_base import ApiExampleBase, MY_DIR, ARTIFACTS_DIR, GOLDS_DIR
from document_helper import DocumentHelper
class ExStructuredDocumentTag(ApiExampleBase):
def test_repeating_section(self):
#ExStart
#ExFor:StructuredDocumentTag.sdt_type
#ExSummary:Shows how to get the type of a structured document tag.
doc = aw.Document(MY_DIR + "Structured document tags.docx")
sd_tags = [node.as_structured_document_tag() for node in doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG, True)]
self.assertEqual(aw.markup.SdtType.REPEATING_SECTION, sd_tags[0].sdt_type)
self.assertEqual(aw.markup.SdtType.REPEATING_SECTION_ITEM, sd_tags[1].sdt_type)
self.assertEqual(aw.markup.SdtType.RICH_TEXT, sd_tags[2].sdt_type)
#ExEnd
def test_apply_style(self):
#ExStart
#ExFor:StructuredDocumentTag
#ExFor:StructuredDocumentTag.node_type
#ExFor:StructuredDocumentTag.style
#ExFor:StructuredDocumentTag.style_name
#ExFor:MarkupLevel
#ExFor:SdtType
#ExSummary:Shows how to work with styles for content control elements.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# Below are two ways to apply a style from the document to a structured document tag.
# 1 - Apply a style object from the document's style collection:
quote_style = doc.styles.get_by_style_identifier(aw.StyleIdentifier.QUOTE)
sdt_plain_text = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.INLINE)
sdt_plain_text.style = quote_style
# 2 - Reference a style in the document by name:
sdt_rich_text = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.RICH_TEXT, aw.markup.MarkupLevel.INLINE)
sdt_rich_text.style_name = "Quote"
builder.insert_node(sdt_plain_text)
builder.insert_node(sdt_rich_text)
self.assertEqual(aw.NodeType.STRUCTURED_DOCUMENT_TAG, sdt_plain_text.node_type)
tags = doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG, True)
for node in tags:
sdt = node.as_structured_document_tag()
self.assertEqual(aw.StyleIdentifier.QUOTE, sdt.style.style_identifier)
self.assertEqual("Quote", sdt.style_name)
#ExEnd
def test_check_box(self):
#ExStart
#ExFor:StructuredDocumentTag.__init__(DocumentBase,SdtType,MarkupLevel)
#ExFor:StructuredDocumentTag.checked
#ExFor:StructuredDocumentTag.set_checked_symbol(int,str)
#ExFor:StructuredDocumentTag.set_unchecked_symbol(int,str)
#ExSummary:Show how to create a structured document tag in the form of a check box.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
sdt_check_box = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.CHECKBOX, aw.markup.MarkupLevel.INLINE)
sdt_check_box.checked = True
# We can set the symbols used to represent the checked/unchecked state of a checkbox content control.
sdt_check_box.set_checked_symbol(0x00A9, "Times New Roman")
sdt_check_box.set_unchecked_symbol(0x00AE, "Times New Roman")
builder.insert_node(sdt_check_box)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.check_box.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.check_box.docx")
tags = [node.as_structured_document_tag() for node in doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG, True)]
self.assertTrue(tags[0].checked)
self.assertEqual(tags[0].xml_mapping.store_item_id, "")
def test_date(self):
#ExStart
#ExFor:StructuredDocumentTag.calendar_type
#ExFor:StructuredDocumentTag.date_display_format
#ExFor:StructuredDocumentTag.date_display_locale
#ExFor:StructuredDocumentTag.date_storage_format
#ExFor:StructuredDocumentTag.full_date
#ExSummary:Shows how to prompt the user to enter a date with a structured document tag.
doc = aw.Document()
# Insert a structured document tag that prompts the user to enter a date.
# In Microsoft Word, this element is known as a "Date picker content control".
# When we click on the arrow on the right end of this tag in Microsoft Word,
# we will see a pop up in the form of a clickable calendar.
# We can use that popup to select a date that the tag will display.
sdt_date = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.DATE, aw.markup.MarkupLevel.INLINE)
# Display the date, according to the Saudi Arabian Arabic locale.
sdt_date.date_display_locale = 1025 #CultureInfo.get_culture_info("ar-SA").LCID
# Set the format with which to display the date.
sdt_date.date_display_format = "dd MMMM, yyyy"
sdt_date.date_storage_format = aw.markup.SdtDateStorageFormat.DATE_TIME
# Display the date according to the Hijri calendar.
sdt_date.calendar_type = aw.markup.SdtCalendarType.HIJRI
# Before the user chooses a date in Microsoft Word, the tag will display the text "Click here to enter a date.".
# According to the tag's calendar, set the "full_date" property to get the tag to display a default date.
sdt_date.full_date = datetime(1440, 10, 20)
builder = aw.DocumentBuilder(doc)
builder.insert_node(sdt_date)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.date.docx")
#ExEnd
def test_plain_text(self):
#ExStart
#ExFor:StructuredDocumentTag.color
#ExFor:StructuredDocumentTag.contents_font
#ExFor:StructuredDocumentTag.end_character_font
#ExFor:StructuredDocumentTag.id
#ExFor:StructuredDocumentTag.level
#ExFor:StructuredDocumentTag.multiline
#ExFor:StructuredDocumentTag.tag
#ExFor:StructuredDocumentTag.title
#ExFor:StructuredDocumentTag.remove_self_only
#ExFor:StructuredDocumentTag.appearance
#ExSummary:Shows how to create a structured document tag in a plain text box and modify its appearance.
doc = aw.Document()
# Create a structured document tag that will contain plain text.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.INLINE)
# Set the title and color of the frame that appears when you mouse over the structured document tag in Microsoft Word.
tag.title = "My plain text"
tag.color = drawing.Color.magenta
# Set a tag for this structured document tag, which is obtainable
# as an XML element named "tag", with the string below in its "@val" attribute.
tag.tag = "MyPlainTextSDT"
# Every structured document tag has a random unique ID.
self.assertGreater(tag.id, 0)
# Set the font for the text inside the structured document tag.
tag.contents_font.name = "Arial"
# Set the font for the text at the end of the structured document tag.
# Any text that we type in the document body after moving out of the tag with arrow keys will use this font.
tag.end_character_font.name = "Arial Black"
# By default, this is False and pressing enter while inside a structured document tag does nothing.
# When set to True, our structured document tag can have multiple lines.
# Set the "multiline" property to "False" to only allow the contents
# of this structured document tag to span a single line.
# Set the "multiline" property to "True" to allow the tag to contain multiple lines of content.
tag.multiline = True
# Set the "Appearance" property to "SdtAppearance.TAGS" to show tags around content.
# By default structured document tag shows as BoundingBox.
tag.appearance = aw.markup.SdtAppearance.TAGS
builder = aw.DocumentBuilder(doc)
builder.insert_node(tag)
# Insert a clone of our structured document tag in a new paragraph.
tag_clone = tag.clone(True).as_structured_document_tag()
builder.insert_paragraph()
builder.insert_node(tag_clone)
# Use the "remove_self_only" method to remove a structured document tag, while keeping its contents in the document.
tag_clone.remove_self_only()
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.plain_text.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.plain_text.docx")
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertEqual("My plain text", tag.title)
self.assertEqual(drawing.Color.magenta.to_argb(), tag.color.to_argb())
self.assertEqual("MyPlainTextSDT", tag.tag)
self.assertGreater(tag.id, 0)
self.assertEqual("Arial", tag.contents_font.name)
self.assertEqual("Arial Black", tag.end_character_font.name)
self.assertTrue(tag.multiline)
self.assertTrue(aw.markup.SdtAppearance.TAGS, tag.appearance)
def test_is_temporary(self):
for is_temporary in (False, True):
with self.subTest(is_temporary=is_temporary):
#ExStart
#ExFor:StructuredDocumentTag.is_temporary
#ExSummary:Shows how to make single-use controls.
doc = aw.Document()
# Insert a plain text structured document tag,
# which will act as a plain text form that the user may enter text into.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.INLINE)
# Set the "is_temporary" property to "True" to make the structured document tag disappear and
# assimilate its contents into the document after the user edits it once in Microsoft Word.
# Set the "is_temporary" property to "False" to allow the user to edit the contents
# of the structured document tag any number of times.
tag.is_temporary = is_temporary
builder = aw.DocumentBuilder(doc)
builder.write("Please enter text: ")
builder.insert_node(tag)
# Insert another structured document tag in the form of a check box and set its default state to "checked".
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.CHECKBOX, aw.markup.MarkupLevel.INLINE)
tag.checked = True
# Set the "is_temporary" property to "True" to make the check box become a symbol
# once the user clicks on it in Microsoft Word.
# Set the "is_temporary" property to "False" to allow the user to click on the check box any number of times.
tag.is_temporary = is_temporary
builder.write("\nPlease click the check box: ")
builder.insert_node(tag)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.is_temporary.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.is_temporary.docx")
self.assertEqual(2, len([sdt.as_structured_document_tag().is_temporary == is_temporary for sdt in doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG, True)]))
def test_placeholder_building_block(self):
for is_showing_placeholder_text in (False, True):
with self.subTest(is_showing_placeholder_text=is_showing_placeholder_text):
#ExStart
#ExFor:StructuredDocumentTag.is_showing_placeholder_text
#ExFor:StructuredDocumentTag.placeholder
#ExFor:StructuredDocumentTag.placeholder_name
#ExSummary:Shows how to use a building block's contents as a custom placeholder text for a structured document tag.
doc = aw.Document()
# Insert a plain text structured document tag of the "PLAIN_TEXT" type, which will function as a text box.
# The contents that it will display by default are a "Click here to enter text." prompt.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.INLINE)
# We can get the tag to display the contents of a building block instead of the default text.
# First, add a building block with contents to the glossary document.
glossary_doc = doc.glossary_document
substitute_block = aw.buildingblocks.BuildingBlock(glossary_doc)
substitute_block.name = "Custom Placeholder"
substitute_block.append_child(aw.Section(glossary_doc))
substitute_block.first_section.append_child(aw.Body(glossary_doc))
substitute_block.first_section.body.append_paragraph("Custom placeholder text.")
glossary_doc.append_child(substitute_block)
# Then, use the structured document tag's "placeholder_name" property to reference that building block by name.
tag.placeholder_name = "Custom Placeholder"
# If "placeholder_name" refers to an existing block in the parent document's glossary document,
# we will be able to verify the building block via the "placeholder" property.
self.assertEqual(substitute_block, tag.placeholder)
# Set the "is_showing_placeholder_text" property to "True" to treat the
# structured document tag's current contents as placeholder text.
# This means that clicking on the text box in Microsoft Word will immediately highlight all the tag's contents.
# Set the "is_showing_placeholder_text" property to "False" to get the
# structured document tag to treat its contents as text that a user has already entered.
# Clicking on this text in Microsoft Word will place the blinking cursor at the clicked location.
tag.is_showing_placeholder_text = is_showing_placeholder_text
builder = aw.DocumentBuilder(doc)
builder.insert_node(tag)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.placeholder_building_block.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.placeholder_building_block.docx")
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
substitute_block = doc.glossary_document.get_child(aw.NodeType.BUILDING_BLOCK, 0, True).as_building_block()
self.assertEqual("Custom Placeholder", substitute_block.name)
self.assertEqual(is_showing_placeholder_text, tag.is_showing_placeholder_text)
self.assertEqual(substitute_block, tag.placeholder)
self.assertEqual(substitute_block.name, tag.placeholder_name)
def test_lock(self):
#ExStart
#ExFor:StructuredDocumentTag.lock_content_control
#ExFor:StructuredDocumentTag.lock_contents
#ExSummary:Shows how to apply editing restrictions to structured document tags.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# Insert a plain text structured document tag, which acts as a text box that prompts the user to fill it in.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.INLINE)
# Set the "lock_contents" property to "True" to prohibit the user from editing this text box's contents.
tag.lock_contents = True
builder.write("The contents of this structured document tag cannot be edited: ")
builder.insert_node(tag)
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.INLINE)
# Set the "lock_content_control" property to "True" to prohibit the user from
# deleting this structured document tag manually in Microsoft Word.
tag.lock_content_control = True
builder.insert_paragraph()
builder.write("This structured document tag cannot be deleted but its contents can be edited: ")
builder.insert_node(tag)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.lock.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.lock.docx")
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertTrue(tag.lock_contents)
self.assertFalse(tag.lock_content_control)
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 1, True).as_structured_document_tag()
self.assertFalse(tag.lock_contents)
self.assertTrue(tag.lock_content_control)
def test_list_item_collection(self):
#ExStart
#ExFor:SdtListItem
#ExFor:SdtListItem.__init__(str)
#ExFor:SdtListItem.__init__(str,str)
#ExFor:SdtListItem.display_text
#ExFor:SdtListItem.value
#ExFor:SdtListItemCollection
#ExFor:SdtListItemCollection.add(SdtListItem)
#ExFor:SdtListItemCollection.clear
#ExFor:SdtListItemCollection.count
#ExFor:SdtListItemCollection.__iter__
#ExFor:SdtListItemCollection.__getitem__(int)
#ExFor:SdtListItemCollection.remove_at(int)
#ExFor:SdtListItemCollection.selected_value
#ExFor:StructuredDocumentTag.list_items
#ExSummary:Shows how to work with drop down-list structured document tags.
doc = aw.Document()
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.DROP_DOWN_LIST, aw.markup.MarkupLevel.BLOCK)
doc.first_section.body.append_child(tag)
# A drop-down list structured document tag is a form that allows the user to
# select an option from a list by left-clicking and opening the form in Microsoft Word.
# The "list_items" property contains all list items, and each list item is an "SdtListItem".
list_items = tag.list_items
list_items.add(aw.markup.SdtListItem("Value 1"))
self.assertEqual(list_items[0].display_text, list_items[0].value)
# Add 3 more list items. Initialize these items using a different constructor to the first item
# to display strings that are different from their values.
list_items.add(aw.markup.SdtListItem("Item 2", "Value 2"))
list_items.add(aw.markup.SdtListItem("Item 3", "Value 3"))
list_items.add(aw.markup.SdtListItem("Item 4", "Value 4"))
self.assertEqual(4, list_items.count)
# The drop-down list is displaying the first item. Assign a different list item to the "selected_value" to display it.
list_items.selected_value = list_items[3]
self.assertEqual("Value 4", list_items.selected_value.value)
# Enumerate over the collection and print each element.
for item in list_items:
if item is not None:
print(f"List item: {item.display_text}, value: {item.value}")
# Remove the last list item.
list_items.remove_at(3)
self.assertEqual(3, list_items.count)
# Since our drop-down control is set to display the removed item by default, give it an item to display which exists.
list_items.selected_value = list_items[1]
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.list_item_collection.docx")
# Use the "clear" method to empty the entire drop-down item collection at once.
list_items.clear()
self.assertEqual(0, list_items.count)
#ExEnd
def test_creating_custom_xml(self):
#ExStart
#ExFor:CustomXmlPart
#ExFor:CustomXmlPart.clone
#ExFor:CustomXmlPart.data
#ExFor:CustomXmlPart.id
#ExFor:CustomXmlPart.schemas
#ExFor:CustomXmlPartCollection
#ExFor:CustomXmlPartCollection.add(CustomXmlPart)
#ExFor:CustomXmlPartCollection.add(str,str)
#ExFor:CustomXmlPartCollection.clear
#ExFor:CustomXmlPartCollection.clone
#ExFor:CustomXmlPartCollection.count
#ExFor:CustomXmlPartCollection.get_by_id(str)
#ExFor:CustomXmlPartCollection.__iter__
#ExFor:CustomXmlPartCollection.__getitem__(int)
#ExFor:CustomXmlPartCollection.remove_at(int)
#ExFor:Document.custom_xml_parts
#ExFor:StructuredDocumentTag.xml_mapping
#ExFor:XmlMapping.set_mapping(CustomXmlPart,str,str)
#ExSummary:Shows how to create a structured document tag with custom XML data.
doc = aw.Document()
# Construct an XML part that contains data and add it to the document's collection.
# If we enable the "Developer" tab in Microsoft Word,
# we can find elements from this collection in the "XML Mapping Pane", along with a few default elements.
xml_part_id = str(uuid.uuid4())
xml_part_content = "<root><text>Hello world!</text></root>"
xml_part = doc.custom_xml_parts.add(xml_part_id, xml_part_content)
self.assertEqual(xml_part_content.encode('ascii'), xml_part.data)
self.assertEqual(xml_part_id, xml_part.id)
# Below are two ways to refer to XML parts.
# 1 - By an index in the custom XML part collection:
self.assertEqual(xml_part, doc.custom_xml_parts[0])
# 2 - By GUID:
self.assertEqual(xml_part, doc.custom_xml_parts.get_by_id(xml_part_id))
# Add an XML schema association.
xml_part.schemas.add("http://www.w3.org/2001/XMLSchema")
# Clone a part, and then insert it into the collection.
xml_part_clone = xml_part.clone()
xml_part_clone.id = str(uuid.uuid4())
doc.custom_xml_parts.add(xml_part_clone)
self.assertEqual(2, doc.custom_xml_parts.count)
# Iterate through the collection and print the contents of each part.
for index, part in enumerate(doc.custom_xml_parts):
print(f"XML part index {index}, ID: {part.id}")
print(f"\tContent: {part.data.decode('utf-8')}")
# Use the "remove_at" method to remove the cloned part by index.
doc.custom_xml_parts.remove_at(1)
self.assertEqual(1, doc.custom_xml_parts.count)
# Clone the XML parts collection, and then use the "Clear" method to remove all its elements at once.
custom_xml_parts = doc.custom_xml_parts.clone()
custom_xml_parts.clear()
# Create a structured document tag that will display our part's contents and insert it into the document body.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.BLOCK)
tag.xml_mapping.set_mapping(xml_part, "/root[1]/text[1]", "")
doc.first_section.body.append_child(tag)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.creating_custom_xml.docx")
#ExEnd
self.assertTrue(DocumentHelper.compare_docs(ARTIFACTS_DIR + "StructuredDocumentTag.creating_custom_xml.docx", GOLDS_DIR + "StructuredDocumentTag.CustomXml Gold.docx"))
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.creating_custom_xml.docx")
xml_part = doc.custom_xml_parts[0]
xml_part_id = uuid.UUID(xml_part.id)
self.assertEqual("<root><text>Hello world!</text></root>", xml_part.data.decode('utf-8'))
self.assertEqual("http://www.w3.org/2001/XMLSchema", xml_part.schemas[0])
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertEqual("Hello world!", tag.get_text().strip())
self.assertEqual("/root[1]/text[1]", tag.xml_mapping.xpath)
self.assertEqual("", tag.xml_mapping.prefix_mappings)
self.assertEqual(xml_part.data_checksum, tag.xml_mapping.custom_xml_part.data_checksum)
def test_data_checksum(self):
#ExStart
#ExFor:CustomXmlPart.data_checksum
#ExSummary:Shows how the checksum is calculated in a runtime.
doc = aw.Document()
rich_text = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.RICH_TEXT, aw.markup.MarkupLevel.BLOCK)
doc.first_section.body.append_child(rich_text)
# The checksum is read-only and computed using the data of the corresponding custom XML data part.
rich_text.xml_mapping.set_mapping(doc.custom_xml_parts.add(str(uuid.uuid4()),
"<root><text>ContentControl</text></root>"), "/root/text", "")
checksum = rich_text.xml_mapping.custom_xml_part.data_checksum
print(checksum)
rich_text.xml_mapping.set_mapping(doc.custom_xml_parts.add(str(uuid.uuid4()),
"<root><text>Updated ContentControl</text></root>"), "/root/text", "")
updated_checksum = rich_text.xml_mapping.custom_xml_part.data_checksum
print(updated_checksum)
# We changed the XmlPart of the tag, and the checksum was updated at runtime.
self.assertNotEqual(checksum, updated_checksum)
#ExEnd
def test_xml_mapping(self):
#ExStart
#ExFor:XmlMapping
#ExFor:XmlMapping.custom_xml_part
#ExFor:XmlMapping.delete
#ExFor:XmlMapping.is_mapped
#ExFor:XmlMapping.prefix_mappings
#ExFor:XmlMapping.xpath
#ExSummary:Shows how to set XML mappings for custom XML parts.
doc = aw.Document()
# Construct an XML part that contains text and add it to the document's CustomXmlPart collection.
xml_part_id = str(uuid.uuid4())
xml_part_content = "<root><text>Text element #1</text><text>Text element #2</text></root>"
xml_part = doc.custom_xml_parts.add(xml_part_id, xml_part_content)
self.assertEqual("<root><text>Text element #1</text><text>Text element #2</text></root>", xml_part.data.decode('utf-8'))
# Create a structured document tag that will display the contents of our CustomXmlPart.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.BLOCK)
# Set a mapping for our structured document tag. This mapping will instruct
# our structured document tag to display a portion of the XML part's text contents that the XPath points to.
# In this case, it will be contents of the the second "<text>" element of the first "<root>" element: "Text element #2".
tag.xml_mapping.set_mapping(xml_part, "/root[1]/text[2]", "xmlns:ns='http://www.w3.org/2001/XMLSchema'")
self.assertTrue(tag.xml_mapping.is_mapped)
self.assertEqual(xml_part, tag.xml_mapping.custom_xml_part)
self.assertEqual("/root[1]/text[2]", tag.xml_mapping.xpath)
self.assertEqual("xmlns:ns='http://www.w3.org/2001/XMLSchema'", tag.xml_mapping.prefix_mappings)
# Add the structured document tag to the document to display the content from our custom part.
doc.first_section.body.append_child(tag)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.xml_mapping.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.xml_mapping.docx")
xml_part = doc.custom_xml_parts[0]
xml_part_id = uuid.UUID(xml_part.id)
self.assertEqual("<root><text>Text element #1</text><text>Text element #2</text></root>", xml_part.data.decode('utf-8'))
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertEqual("Text element #2", tag.get_text().strip())
self.assertEqual("/root[1]/text[2]", tag.xml_mapping.xpath)
self.assertEqual("xmlns:ns='http://www.w3.org/2001/XMLSchema'", tag.xml_mapping.prefix_mappings)
def test_structured_document_tag_range_start_xml_mapping(self):
#ExStart
#ExFor:StructuredDocumentTagRangeStart.xml_mapping
#ExSummary:Shows how to set XML mappings for the range start of a structured document tag.
doc = aw.Document(MY_DIR + "Multi-section structured document tags.docx")
# Construct an XML part that contains text and add it to the document's CustomXmlPart collection.
xml_part_id = str(uuid.uuid4())
xml_part_content = "<root><text>Text element #1</text><text>Text element #2</text></root>"
xml_part = doc.custom_xml_parts.add(xml_part_id, xml_part_content)
self.assertEqual("<root><text>Text element #1</text><text>Text element #2</text></root>", xml_part.data.decode('utf-8'))
# Create a structured document tag that will display the contents of our CustomXmlPart in the document.
sdt_range_start = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, 0, True).as_structured_document_tag_range_start()
# If we set a mapping for our structured document tag,
# it will only display a portion of the CustomXmlPart that the XPath points to.
# This XPath will point to the contents second "<text>" element of the first "<root>" element of our CustomXmlPart.
sdt_range_start.xml_mapping.set_mapping(xml_part, "/root[1]/text[2]", None)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.structured_document_tag_range_start_xml_mapping.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.structured_document_tag_range_start_xml_mapping.docx")
xml_part = doc.custom_xml_parts[0]
xml_part_id = uuid.UUID(xml_part.id)
self.assertEqual("<root><text>Text element #1</text><text>Text element #2</text></root>", xml_part.data.decode('utf-8'))
sdt_range_start = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, 0, True).as_structured_document_tag_range_start()
self.assertEqual("/root[1]/text[2]", sdt_range_start.xml_mapping.xpath)
def test_custom_xml_schema_collection(self):
#ExStart
#ExFor:CustomXmlSchemaCollection
#ExFor:CustomXmlSchemaCollection.add(str)
#ExFor:CustomXmlSchemaCollection.clear
#ExFor:CustomXmlSchemaCollection.clone
#ExFor:CustomXmlSchemaCollection.count
#ExFor:CustomXmlSchemaCollection.__iter__
#ExFor:CustomXmlSchemaCollection.index_of(str)
#ExFor:CustomXmlSchemaCollection.__getitem__(int)
#ExFor:CustomXmlSchemaCollection.remove(str)
#ExFor:CustomXmlSchemaCollection.remove_at(int)
#ExSummary:Shows how to work with an XML schema collection.
doc = aw.Document()
xml_part_id = str(uuid.uuid4())
xml_part_content = "<root><text>Hello, World!</text></root>"
xml_part = doc.custom_xml_parts.add(xml_part_id, xml_part_content)
# Add an XML schema association.
xml_part.schemas.add("http://www.w3.org/2001/XMLSchema")
# Clone the custom XML part's XML schema association collection,
# and then add a couple of new schemas to the clone.
schemas = xml_part.schemas.clone()
schemas.add("http://www.w3.org/2001/XMLSchema-instance")
schemas.add("http://schemas.microsoft.com/office/2006/metadata/contentType")
self.assertEqual(3, schemas.count)
self.assertEqual(2, schemas.index_of("http://schemas.microsoft.com/office/2006/metadata/contentType"))
# Enumerate the schemas and print each element.
for schema in schemas:
print(schema)
# Below are three ways of removing schemas from the collection.
# 1 - Remove a schema by index:
schemas.remove_at(2)
# 2 - Remove a schema by value:
schemas.remove("http://www.w3.org/2001/XMLSchema")
# 3 - Use the "clear" method to empty the collection at once.
schemas.clear()
self.assertEqual(0, schemas.count)
#ExEnd
def test_custom_xml_part_store_item_id_read_only(self):
#ExStart
#ExFor:XmlMapping.store_item_id
#ExSummary:Shows how to get the custom XML data identifier of an XML part.
doc = aw.Document(MY_DIR + "Custom XML part in structured document tag.docx")
# Structured document tags have IDs in the form of GUIDs.
tag = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertEqual("{F3029283-4FF8-4DD2-9F31-395F19ACEE85}", tag.xml_mapping.store_item_id)
#ExEnd
def test_custom_xml_part_store_item_id_read_only_null(self):
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
sdt_check_box = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.CHECKBOX, aw.markup.MarkupLevel.INLINE)
sdt_check_box.checked = True
builder.insert_node(sdt_check_box)
doc = DocumentHelper.save_open(doc)
sdt = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
print("The Id of your custom xml part is:", sdt.xml_mapping.store_item_id)
def test_clear_text_from_structured_document_tags(self):
#ExStart
#ExFor:StructuredDocumentTag.clear
#ExSummary:Shows how to delete contents of structured document tag elements.
doc = aw.Document()
# Create a plain text structured document tag, and then append it to the document.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.BLOCK)
doc.first_section.body.append_child(tag)
# This structured document tag, which is in the form of a text box, already displays placeholder text.
self.assertEqual("Click here to enter text.", tag.get_text().strip())
self.assertTrue(tag.is_showing_placeholder_text)
# Create a building block with text contents.
glossary_doc = doc.glossary_document
substitute_block = aw.buildingblocks.BuildingBlock(glossary_doc)
substitute_block.name = "My placeholder"
substitute_block.append_child(aw.Section(glossary_doc))
substitute_block.first_section.ensure_minimum()
substitute_block.first_section.body.first_paragraph.append_child(aw.Run(glossary_doc, "Custom placeholder text."))
glossary_doc.append_child(substitute_block)
# Set the structured document tag's "placeholder_name" property to our building block's name to get
# the structured document tag to display the contents of the building block in place of the original default text.
tag.placeholder_name = "My placeholder"
self.assertEqual("Custom placeholder text.", tag.get_text().strip())
self.assertTrue(tag.is_showing_placeholder_text)
# Edit the text of the structured document tag and hide the placeholder text.
run = tag.get_child(aw.NodeType.RUN, 0, True).as_run()
run.text = "New text."
tag.is_showing_placeholder_text = False
self.assertEqual("New text.", tag.get_text().strip())
# Use the "clear" method to clear this structured document tag's contents and display the placeholder again.
tag.clear()
self.assertTrue(tag.is_showing_placeholder_text)
self.assertEqual("Custom placeholder text.", tag.get_text().strip())
#ExEnd
def test_access_to_building_block_properties_from_doc_part_obj_sdt(self):
doc = aw.Document(MY_DIR + "Structured document tags with building blocks.docx")
doc_part_obj_sdt = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertEqual(aw.markup.SdtType.DOC_PART_OBJ, doc_part_obj_sdt.sdt_type)
self.assertEqual("Table of Contents", doc_part_obj_sdt.building_block_gallery)
def test_access_to_building_block_properties_from_plain_text_sdt(self):
doc = aw.Document(MY_DIR + "Structured document tags with building blocks.docx")
plain_text_sdt = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 1, True).as_structured_document_tag()
self.assertEqual(aw.markup.SdtType.PLAIN_TEXT, plain_text_sdt.sdt_type)
with self.assertRaises(Exception, msg="BuildingBlockType is only accessible for BuildingBlockGallery SDT type."):
building_block_gallery = plain_text_sdt.building_block_gallery
def test_building_block_categories(self):
#ExStart
#ExFor:StructuredDocumentTag.building_block_category
#ExFor:StructuredDocumentTag.building_block_gallery
#ExSummary:Shows how to insert a structured document tag as a building block, and set its category and gallery.
doc = aw.Document()
building_block_sdt = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.BUILDING_BLOCK_GALLERY, aw.markup.MarkupLevel.BLOCK)
building_block_sdt.building_block_category = "Built-in"
building_block_sdt.building_block_gallery = "Table of Contents"
doc.first_section.body.append_child(building_block_sdt)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.BuildingBlockCategories.docx")
#ExEnd
building_block_sdt = doc.first_section.body.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG, 0, True).as_structured_document_tag()
self.assertEqual(aw.markup.SdtType.BUILDING_BLOCK_GALLERY, building_block_sdt.sdt_type)
self.assertEqual("Table of Contents", building_block_sdt.building_block_gallery)
self.assertEqual("Built-in", building_block_sdt.building_block_category)
def test_update_sdt_content(self):
for update_sdt_content in (False, True):
with self.subTest(update_sdt_content=update_sdt_content):
#ExStart
#ExFor:SaveOptions.update_sdt_content
#ExSummary:Shows how to update structured document tags while saving a document to PDF.
doc = aw.Document()
# Insert a drop-down list structured document tag.
tag = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.DROP_DOWN_LIST, aw.markup.MarkupLevel.BLOCK)
tag.list_items.add(aw.markup.SdtListItem("Value 1"))
tag.list_items.add(aw.markup.SdtListItem("Value 2"))
tag.list_items.add(aw.markup.SdtListItem("Value 3"))
# The drop-down list currently displays "Choose an item" as the default text.
# Set the "selected_value" property to one of the list items to get the tag to
# display that list item's value instead of the default text.
tag.list_items.selected_value = tag.list_items[1]
doc.first_section.body.append_child(tag)
# Create a "PdfSaveOptions" object to pass to the document's "Save" method
# to modify how that method saves the document to .PDF.
options = aw.saving.PdfSaveOptions()
# Set the "update_sdt_content" property to "False" not to update the structured document tags
# while saving the document to PDF. They will display their default values as they were at the time of construction.
# Set the "update_sdt_content" property to "True" to make sure the tags display updated values in the PDF.
options.update_sdt_content = update_sdt_content
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.update_sdt_content.pdf", options)
#ExEnd
#pdf_doc = aspose.pdf.Document(ARTIFACTS_DIR + "StructuredDocumentTag.UpdateSdtContent.pdf")
#text_absorber = aspose.pdf.text.TextAbsorber()
#text_absorber.visit(pdf_doc)
#self.assertEqual(
# "Value 2" if update_sdt_content else "Choose an item.",
# text_absorber.text)
def test_fill_table_using_repeating_section_item(self):
#ExStart
#ExFor:SdtType
#ExSummary:Shows how to fill a table with data from in an XML part.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
xml_part = doc.custom_xml_parts.add("Books",
"<books>" +
"<book>" +
"<title>Everyday Italian</title>" +
"<author><NAME></author>" +
"</book>" +
"<book>" +
"<title>The C Programming Language</title>" +
"<author><NAME>, <NAME></author>" +
"</book>" +
"<book>" +
"<title>Learning XML</title>" +
"<author><NAME></author>" +
"</book>" +
"</books>")
# Create headers for data from the XML content.
table = builder.start_table()
builder.insert_cell()
builder.write("Title")
builder.insert_cell()
builder.write("Author")
builder.end_row()
builder.end_table()
# Create a table with a repeating section inside.
repeating_section_sdt = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.REPEATING_SECTION, aw.markup.MarkupLevel.ROW)
repeating_section_sdt.xml_mapping.set_mapping(xml_part, "/books[1]/book", "")
table.append_child(repeating_section_sdt)
# Add repeating section item inside the repeating section and mark it as a row.
# This table will have a row for each element that we can find in the XML document
# using the "/books[1]/book" XPath, of which there are three.
repeating_section_item_sdt = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.REPEATING_SECTION_ITEM, aw.markup.MarkupLevel.ROW)
repeating_section_sdt.append_child(repeating_section_item_sdt)
row = aw.tables.Row(doc)
repeating_section_item_sdt.append_child(row)
# Map XML data with created table cells for the title and author of each book.
title_sdt = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.CELL)
title_sdt.xml_mapping.set_mapping(xml_part, "/books[1]/book[1]/title[1]", "")
row.append_child(title_sdt)
author_sdt = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.CELL)
author_sdt.xml_mapping.set_mapping(xml_part, "/books[1]/book[1]/author[1]", "")
row.append_child(author_sdt)
doc.save(ARTIFACTS_DIR + "StructuredDocumentTag.fill_table_using_repeating_section_item.docx")
#ExEnd
doc = aw.Document(ARTIFACTS_DIR + "StructuredDocumentTag.fill_table_using_repeating_section_item.docx")
tags = [node.as_structured_document_tag() for node in doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG, True)]
self.assertEqual("/books[1]/book", tags[0].xml_mapping.xpath)
self.assertEqual("", tags[0].xml_mapping.prefix_mappings)
self.assertEqual("", tags[1].xml_mapping.xpath)
self.assertEqual("", tags[1].xml_mapping.prefix_mappings)
self.assertEqual("/books[1]/book[1]/title[1]", tags[2].xml_mapping.xpath)
self.assertEqual("", tags[2].xml_mapping.prefix_mappings)
self.assertEqual("/books[1]/book[1]/author[1]", tags[3].xml_mapping.xpath)
self.assertEqual("", tags[3].xml_mapping.prefix_mappings)
self.assertEqual("Title\u0007Author\u0007\u0007" +
"Everyday Italian\u0007Giada De Laurentiis\u0007\u0007" +
"The C Programming Language\u0007<NAME>, <NAME>\u0007\u0007" +
"Learning XML\u0007E<NAME>\u0007\u0007", doc.first_section.body.tables[0].get_text().strip())
def test_custom_xml_part(self):
xml_string = ("<?xml version=\"1.0\"?>" +
"<Company>" +
"<Employee id=\"1\">" +
"<FirstName>John</FirstName>" +
"<LastName>Doe</LastName>" +
"</Employee>" +
"<Employee id=\"2\">" +
"<FirstName>Jane</FirstName>" +
"<LastName>Doe</LastName>" +
"</Employee>" +
"</Company>")
doc = aw.Document()
# Insert the full XML document as a custom document part.
# We can find the mapping for this part in Microsoft Word via "Developer" -> "XML Mapping Pane", if it is enabled.
xml_part = doc.custom_xml_parts.add(str(uuid.uuid4()), xml_string)
# Create a structured document tag, which will use an XPath to refer to a single element from the XML.
sdt = aw.markup.StructuredDocumentTag(doc, aw.markup.SdtType.PLAIN_TEXT, aw.markup.MarkupLevel.BLOCK)
sdt.xml_mapping.set_mapping(xml_part, "Company//Employee[@id='2']/FirstName", "")
# Add the StructuredDocumentTag to the document to display the element in the text.
doc.first_section.body.append_child(sdt)
def test_multi_section_tags(self):
#ExStart
#ExFor:StructuredDocumentTagRangeStart
#ExFor:StructuredDocumentTagRangeStart.id
#ExFor:StructuredDocumentTagRangeStart.title
#ExFor:StructuredDocumentTagRangeStart.placeholder_name
#ExFor:StructuredDocumentTagRangeStart.is_showing_placeholder_text
#ExFor:StructuredDocumentTagRangeStart.lock_content_control
#ExFor:StructuredDocumentTagRangeStart.lock_contents
#ExFor:StructuredDocumentTagRangeStart.level
#ExFor:StructuredDocumentTagRangeStart.range_end
#ExFor:StructuredDocumentTagRangeStart.color
#ExFor:StructuredDocumentTagRangeStart.sdt_type
#ExFor:StructuredDocumentTagRangeStart.tag
#ExFor:StructuredDocumentTagRangeEnd
#ExFor:StructuredDocumentTagRangeEnd.id
#ExSummary:Shows how to get the properties of multi-section structured document tags.
doc = aw.Document(MY_DIR + "Multi-section structured document tags.docx")
range_start_tag = doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, True)[0].as_structured_document_tag_range_start()
range_end_tag = doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_END, True)[0].as_structured_document_tag_range_end()
self.assertEqual(range_start_tag.id, range_end_tag.id) #ExSkip
self.assertEqual(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, range_start_tag.node_type) #ExSkip
self.assertEqual(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_END, range_end_tag.node_type) #ExSkip
print("StructuredDocumentTagRangeStart values:")
print(f"\t|id: {range_start_tag.id}")
print(f"\t|title: {range_start_tag.title}")
print(f"\t|placeholder_name: {range_start_tag.placeholder_name}")
print(f"\t|is_showing_placeholder_text: {range_start_tag.is_showing_placeholder_text}")
print(f"\t|lock_content_control: {range_start_tag.lock_content_control}")
print(f"\t|lock_contents: {range_start_tag.lock_contents}")
print(f"\t|level: {range_start_tag.level}")
print(f"\t|node_type: {range_start_tag.node_type}")
print(f"\t|range_end: {range_start_tag.range_end}")
print(f"\t|color: {range_start_tag.color.to_argb()}")
print(f"\t|sdt_type: {range_start_tag.sdt_type}")
print(f"\t|tag: {range_start_tag.tag}\n")
print("StructuredDocumentTagRangeEnd values:")
print(f"\t|id: {range_end_tag.id}")
print(f"\t|node_type: {range_end_tag.node_type}")
#ExEnd
def test_sdt_child_nodes(self):
#ExStart
#ExFor:StructuredDocumentTagRangeStart.child_nodes
#ExFor:StructuredDocumentTagRangeStart.get_child_nodes(NodeType,bool)
#ExSummary:Shows how to get child nodes of StructuredDocumentTagRangeStart.
doc = aw.Document(MY_DIR + "Multi-section structured document tags.docx")
tag = doc.get_child_nodes(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, True)[0].as_structured_document_tag_range_start()
print("StructuredDocumentTagRangeStart values:")
print(f"\t|Child nodes count: {tag.child_nodes.count}\n")
for node in tag.child_nodes:
print(f"\t|Child node type: {node.node_type}")
for node in tag.get_child_nodes(aw.NodeType.RUN, True):
print(f"\t|Child node text: {node.get_text()}")
#ExEnd
#ExStart
#ExFor:StructuredDocumentTagRangeStart.__init__(DocumentBase,SdtType)
#ExFor:StructuredDocumentTagRangeEnd.__init__(DocumentBase,int)
#ExFor:StructuredDocumentTagRangeStart.remove_self_only
#ExFor:StructuredDocumentTagRangeStart.remove_all_children
#ExSummary:Shows how to create/remove structured document tag and its content.
def test_sdt_range_extended_methods(self):
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.writeln("StructuredDocumentTag element")
range_start = self.insert_structured_document_tag_ranges(doc)
# Removes ranged structured document tag, but keeps content inside.
range_start.remove_self_only()
range_start = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_START, 0, False)
self.assertIsNone(range_start)
range_end = doc.get_child(aw.NodeType.STRUCTURED_DOCUMENT_TAG_RANGE_END, 0, False)
self.assertIsNone(range_end)
self.assertEqual("StructuredDocumentTag element", doc.get_text().strip())
range_start = self.insert_structured_document_tag_ranges(doc)
paragraph_node = range_start.last_child
self.assertEqual("StructuredDocumentTag element", paragraph_node.get_text().strip())
# Removes ranged structured document tag and content inside.
range_start.remove_all_children()
paragraph_node = range_start.last_child
self.assertIsNone(None, paragraph_node.get_text())
def insert_structured_document_tag_ranges(self, doc: aw.Document) -> aw.markup.StructuredDocumentTagRangeStart:
range_start = aw.markup.StructuredDocumentTagRangeStart(doc, aw.markup.SdtType.PLAIN_TEXT)
range_end = aw.markup.StructuredDocumentTagRangeEnd(doc, range_start.id)
doc.first_section.body.insert_before(range_start, doc.first_section.body.first_paragraph)
doc.last_section.body.insert_after(range_end, doc.first_section.body.first_paragraph)
return range_start
#ExEnd
|
python
|
New Delhi: India plans a major vaccination drive against COVID-19 which struck the country nearly a year ago. The entire process might take one year or even more. For vaccine distribution, the authorities will emulate the modalities of conducting elections so that all the eligible people residing even at the lowest administrative unit, the village or municipal ward, are covered. The lessons from the Universal Immunization Programme could also come in handy.
India has short-listed six vaccines which are being tested on humans and three vaccines which are in the pre-clinical trial stage. Of these most require two shots and the one manufactured by Zydus Cadila requires three.
Awareness programmes are of utmost importance in India which is all set to enter the crucial phase of COVID-19 vaccine distribution soon, Union health secretary Rajesh Bhushan stated.
He said the major challenge before the country is to create awareness among the people about the possible side effects that all vaccines may have and curbing the fake propaganda against the vaccine.
The existing health services will not get affected. There won't be any compromise on regulatory and scientific measures, the government has assured.
Up to 30 minutes time would be required for administering the vaccine to each person. This is also to monitor the side effects. Up to 100 persons will be vaccinated in each session at the vaccination centres.
Who will administer the vaccine?
At present 2. 39 lakh midwives are engaged for the Universal Immunization Programme. Of these, 1. 54 lakh will be deployed for COVID vaccination. More people would be made available by the respective state governments.
The country has 28,947 cold chain points for storing vaccines.
Allied equipment includes coolers, freezers, deep freezers, ice-lined refrigerators and cold storage trucks. They number 85, 634. More facilities will be provided by the states.
Six crore doses could be stored in the existing facilities and they are enough for the first 3 crore people who will be administered the vaccine.
Even though a three-tier system comprising state-, district- and block-level authorities will be put in place, it will function under the National Expert Committee constituted for vaccine administration.
The chief secretary will be the chairman of the state-level committee. The principal secretary (health department) will be the chairman of the working group and will oversee the control rooms.
Similar committees will be constituted at the district and block level. Collector and tahsildar will head the committees here.
Control rooms will function at all levels. The district-level committee will meet on December 12 and at the block level on December 15.
The process of vaccine distribution is being given the final touches. Additional storage of syringes and needles has begun. Training tools will be made available.
Covin software and application has been put in place for collecting all details about vaccines. It has the capability to monitor and evaluate the temperature variation in each vaccine storage centre.
The central government has softened its earlier stand that COVID vaccines will not be approved without trials in India.
Union health secretary Rajesh Bhushan said that there are laws to even exempt trials among humans and if required emergency permission will be granted. The health secretary’s reaction comes in the wake of vaccine companies approaching for permission without completing trials and conducting trials in India.
The pharma companies that have sought permission for emergency use in India are Pfizer which has started vaccine distribution in Britain; Serum Institute which is manufacturing Covishield developed by Oxford; and Bharat Biotech that is developing India's indigenous vaccine Covaxin.
The union health secretary also clarified that though talks have begun with companies over the COVID vaccine price in India, no decision has been taken yet.
The central government will procure vaccines from various companies. The centre will be distributing the vaccine to the states. "We expect the companies to make vaccines available to the government at an affordable price," he told Manorama.
Covishield maker has informed that it would be able to supply a certain amount of vaccines at Rs 225. Serum Institute CEO Adar Poonawala said two shots of another vaccine will be made available below Rs 1,000. The company aims to bring the vaccine to the open market by February or March.
|
english
|
Ronki Ram is the Shaheed Bhagat Singh professor at the Department of Political Science at Panjab University and has written extensively on the deras of Punjab – religious centres with living gurus.
In this interview, he talks to Scroll.in about how deras have become the nucleus of Dalit assertion, on the growing significance of deras in Punjab’s socio-political landscape and the challenges that the rise of new religions pose to the established faiths in Punjab.
What is the etymology of the word dera?
The word dera today has a different connotation than before. You might have heard of Dera Ghazi Khan and Dera Ismail Khan, which are in Pakistan today. In this context, dera means a space where people reside.
Later on, dera came to imply a space where Sufis, or spiritual men, would gather. It was also called a majlis, where food was provided, accommodation was given to visiting strangers and esoteric matters were discussed – for instance, how to better one’s life or aspects of the unknown. The origin of dera is most likely Persian.
A place of worship has certain architectural features that make us identify it as a gurudwara or temple or mosque or church. Do deras have such features?
Deras have their own unique architectural features. It would, to begin with, not have a formal structure. It could simply be a thatched hut. Or it may have just a boundary wall with a kuttcha roof (or canopy). It could also have brick-mortar rooms and halls with modern amenities – for instance, Dera Sacha Sauda or Dera Ballan.
Deras may also have structures that combine elements of the architectural style of temples and gurudwaras. Deras consciously want to distinguish themselves from both. Deras seek to establish that they are alternative religious sites. To become potent sites, deras need to have their own structures.
A religion usually has a holy book, or books, and forms of worship. What are the socio-philosophical principles around which deras are organised?
A dera is organised around the holy person who heads it. He – whether a baba or guru – epitomises the dera. The guru professes some philosophy and scriptural bani [utterances and writings of gurus]. His bani often contain portions from different scriptures already in existence.
In that sense, deras are syncretic.
Yes, they are syncretic. This is because followers of a dera need not leave the religion to which they belong. A dera could be headed by a Sikh, a Muslim, a Christian or a Buddhist.
However, over the years, gradually, some deras identify themselves as separate faiths. An example of this is Dera Sachkhand Ballan. It has adopted a religion called the Ravidassia dharam. It started as a syncretic movement, but has gone on to carve out its own path.
It involved Ravidassias declaring themselves as belonging to a separate faith, didn’t it?
Yes, but what I wish to underline is that deras are in the process of becoming new religions (or forms of a new religion). The Dera Sachkhand Ballan represents this trend.
In a 2007 essay, you wrote that Punjab has many as 9,000 deras.
It is definitely more now, over 10,000 perhaps.
In one of your essays, you distinguish between Sikh deras and non-Sikh deras. Among the non-Sikh deras you include those of the Radha Soamis, Sacha Sauda, Nirankaris, Namdharis, Bhaniarawala and Ravidassias. What is the basis of this categorisation?
The Sikh deras primarily follow the Sikh code of conduct. Although they are run by spiritual men, it is the Guru Granth Sahib that is in the forefront. The spiritual presence in these deras is that of the Guru Granth Sahib, not of the babas. The baba is only the coordinator, the caretaker of the holy place, even though it is named after him. He does not constitute the spirit of his own dera.
What about the Nirankaris and the Namdharis? They are popularly perceived to be Sikhs but you have categorised their deras as non-Sikh.
The Nirankaris and the Namdharis consider their babas as living gods and gurus. In the Sikh tradition, the line of gurus came to an end with the tenth guru (Guru Gobind Singh). Thereafter, the Guru Granth Sahib became the eleventh or eternal guru. But the Nirankaris and the Namdharis continued with the tradition of gurus. What’s more, they consider a living human being as a guru. It is not that the Guru Granth Sahib is unacceptable to them. But their tradition of having a living guru is in contravention of the Sikh tradition.
Wasn’t it the idea of a living guru that led to the attack on Sant Niranjan Dass, head of the Dera Sachkhand Ballan and his deputy, Sant Ramanand, in Vienna in 2009 – and in which the latter died?
Yes, the assailants and their supporters argued about why Sant Niranjan Dass should consider himself to be a living guru and not accept the Guru Granth Sahib [as the eternal guru]. Their questions were: Why isn’t Sant Dass merely acting as chief coordinator or sarsanghchalak? Why isn’t he accepting [the supremacy of] the Guru Granth Sahib? Why have they compiled their separate bani called Amrit Bani Guru Ravidass?
Wasn’t it after the attack of 2009 that the Dera Sachkhand Ballan declared itself as a separate religion?
Yes, because of the attack in Vienna, the Ravidassias declared in 2010 that theirs is a separate religion.
But before 2010, would they have been considered Sikh?
No. They did sport long hair, but some of them were also clean-shaven. They wore long kurtas and their iconography resembled that of the Sikhs, but they never considered themselves as belonging to the Sikh faith. They called themselves Ravidassias.
But others considered them to be Sikhs. In my ethnographic studies I tried to clarify that they may look like Sikhs, but they are not so. After all, long hair is in the Hindu tradition as well. Didn’t some Hindu Mahatmas keep their hair long? They would also cover their heads with a cloth. Being a Sikh is not just about wearing the turban.
So what you are saying is that people erroneously think a person is Sikh only because he happens to wear the turban. The definition of who is a Sikh is far wider than that.
Let me explain it through a parallel. All the white people in North America think that those who have a beard and sport a turban are Taliban. In America, Sikhs are mistaken for Taliban. In India, some people are mistaken for Sikhs because they look like them.
In several of your essays you have linked the proliferation of deras to Dalit assertion. Why has Dalit assertion been through deras? What kind of socio-psychological needs do deras satisfy?
If you study any social or political movement in India, you will find it has some links to religion at the time of its launch. For example, the Indian Renaissance movement of Raja Ram Mohun Roy gradually led to the national movement constructing the idea of Bharat Mata, who was projected as a goddess. This goddess was linked to Shakti. That Shakti had emerged from lord Shiva. The people of India immediately accepted it.
People from subaltern social groups sought social mobility by converting to Christianity, Islam and Sikhism. But even after their conversion, they realised their social status still remained the same and untouchability still prevailed.
They, therefore, asked themselves: What should we do to enhance our social status? They thought mobility could be achieved through the social agency of a new religion. Its initial form was the dera. However, a dera is not a place where they merely go to perform religious ceremonies. It’s also a venue of social gathering where nobody discriminates against them. They consider it as a place that is their own.
Isn’t the dera also a symbol of protest against social discrimination practiced in gurudwaras?
I see it as an attempt by subaltern social groups to carve out a separate space for themselves, to create an identity for themselves. For centuries, they were denied an independent identity. They are now creating a separate identity through the dera. This effort is often understood as protest.
During which period did the proliferation of deras begin?
It began with the rise of the Green Revolution, the migration of Dalits to European, North American and Arab countries, and with the maturation of the reservation policy. It provided them money to live comfortably. But they also realised that despite being in government jobs and business or in professions, they were not given importance because they happened to be from lower castes. They continued to live in separate colonies. Entry to public places was still denied to them.
They, therefore, purchased 25 kg of gold and turned it into a murti, or statue of Sant Ravidas and installed it in the temple at his birthplace in Goverdhanpur village, Varanasi, in 2008. Similarly, 25 kg of gold was turned into a murti and placed in Dera Ballan in 2008.
Why do the Shiromani Gurdwara Parbandhak Committee and seminaries such as Damdami Taksal resent deras?
Because the deras are mushrooming and expanding and they’re also making the social boundaries increasingly porous. They are attracting not only Ravidassias, but others as well. Punjabis are not communal. They are essentially a syncretic people [because every foreign conqueror passed through Punjab]. People other than Ravidassias, too, started going to the deras.
Assume a place has two temples, two gurudwaras and a dera. Since some of those who were earlier going to temples or gurudwaras began visiting the dera, the political economy of religion was affected. Deras began to adversely affect the offerings at other places of worship.
Even some of the upper castes have started going to the deras.
Do upper castes go to deras patronised by, say, Ravidassias, or do they have their own?
Deras revolve around a person considered holy. When his popularity rises, people are attracted to him, regardless of their caste.
I will give you an example. I come from Sahri village in Hoshiarpur. My grandfather had faith in a spiritual person who was considered holy. His name was Baba Mahan Das, who had a dera in the Dalit locality of my village. One day, my grandfather, after milking the cows, was returning home with a bucket of milk. When the dera people asked for some milk, he gave them the entire bucket.
It prompted someone to tell my grandfather, rather sarcastically, that if he was so enamoured of Baba Mahan Das, why didn’t he accept the holy man as his guru?
Mind you, my grandfather was not a Dalit. That should tell you how deras bridge the caste divide.
Has the growing popularity of deras led to rivalry and intense competition among places of worship of different faiths?
Yes, but it is not the followers of different faiths who fight each other. Those who manage the affairs at places of worship fear that the decrease in the number of their followers would lead to a dip in their business. However, once the faultlines emerge, communal clashes take place.
But aren’t the inter-group clashes linked to the fear of Jat Sikhs losing their power?
Punjab has the highest number of Dalits in the country [nearly 33%-34% as against the all-India average of 16%]. Yet, they are discriminated against in the economic realm. The Jat Sikhs are the landlords and Dalits are agricultural labourers. But even Dalits who have prospered realise they are denied equality in the religious realm. They have therefore taken to establishing their deras.
Yes, but doesn’t it arouse the jealousy of Jat Sikhs?
Naturally, deras do arouse the jealousy of Jat Sikhs. People over whom they ruled once are now competing with them. It has to trigger jealousy and rivalry.
Why is it that politicians make a beeline for deras?
Deras have a massive following. But these people are not just followers of babas. They are also husbands and wives, children and parents, businesspersons and employees. They are voters too. Besides being spiritual seekers, they are also looking for social mobility. It is this idea that most influences their voting decisions. When they feel that a particular party ensures them social mobility, they vote for it.
Do you think the trend of babas influencing the voting choices of their followers should be discouraged?
Deras are located in the society, not outside it. No society is apolitical. It is true that some deras have their own leanings and they are quite open about it. Politicians go to deras because it is their way of promising to promote social mobility for dera followers.
Have deras become a device to challenge the Akali Dal’s control over Sikh politics?
No. Non-Sikh deras seek to establish control over their followers as the Akali Dal has over the Sikhs. They are not challenging the Akali Dal. I will draw a parallel here – when Muslims begin to mobilise themselves, non-Muslims begin to feel threatened. It is not that Muslims mobilise against Hindus. Nevertheless, Hindus begin to wonder why Muslims are mobilising. It leads to non-Hindu counter-mobilisation.
This is precisely what is happening in Punjab, too, between non-Sikh deras and Sikh deras. When one group mobilises, other groups attempt the same because of the fear of losing out.
In other words, the proliferation of deras has enhanced political competition.
No doubt, the proliferation of deras has greatly intensified political competition. Deras are giving a voice to those who were not heard earlier in Punjab. These were the people who were taken for granted. But by coming to deras they have become assertive – and this has created a new form of political behaviour in the society. This competition could be conflictual or non-conflictual, depending upon the situation.
Aam Aadmi Party’s Arvind Kejriwal has visited three deras over the last few months. Do you think, as some say, he is mixing politics with religion, something which he has refrained from so far?
Let us face it – deras can’t be ignored as they have a significant socio-political role. That said, very few deras ask their followers to vote for a particular party. Heads of deras mostly say it is not their business to have their followers support one party or the other.
Dera followers, however, think otherwise. [As citizens] they do discuss among themselves about which party suits them most. Also, dera followers are extremely united. So some kind of consensus emerges among them. This is why politicians make a beeline for deras.
However, it is a two-way process. When politicians visit deras for the blessings of their babas, they greatly enhance their importance. But it also makes them syncretic. This is because if the Badals visit a Dera, that doesn’t mean Captain Amrinder Singh or Kejriwal can’t. Then again, along with politicians, many others visit deras and partake of the langar food. It encourages mingling.
You have businesspersons who are at the forefront of several deras. They are rich but feel they do not have the requisite social status. A politician’s visit, in a way, encourages them. At the same time, it triggers fear among established religions that they might be challenged.
It is inevitable for a Badal or a Capt Amrinder or a Kejriwal to visit deras. Deras can’t be isolated from the system, from the government. Several of them are provided security. When Sant Ramanand was killed in Vienna, his body was brought back and cremated with full state honours.
It is also true the other way round – our political structures can’t be insulated from the deras.
|
english
|
<reponame>jbratcher/thrashing-magazine<filename>dist/index.html
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Thrashing Magazine</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro|Source+Serif+Pro" rel="stylesheet">
<link rel="stylesheet" href="css/styles.min.css">
</head>
<body>
<header>
<nav id="nav-left">
<ul>
<li><a href="#news">News</a></li>
<li><a href="#tech">Tech</a></li>
<li><a href="#dev">Dev</a></li>
</ul>
</nav>
<section id="brand">
<h1><em>Thrashing</em> Magazine</h1>
</section>
<nav id="nav-right">
<ul>
<li><a href="#sports">Sports</a></li>
<li><a href="#finance">Finance</a></li>
<li><a href="#politics">Politics</a></li>
</ul>
</nav>
<a href="#nav-mobile" id="menu-toggle" class="toggle"><i class="fa fa-bars fa-2x" aria-hidden="true"></i></a>
<nav id="nav-mobile">
<ul>
<li><a id="nav-close" class="toggle" href="#"><i class="fa fa-times fa-2x"></i></a></li>
<li><a href="#news">News</a></li>
<li><a href="#tech">Tech</a></li>
<li><a href="#dev">Dev</a></li>
<li><a href="#sports">Sports</a></li>
<li><a href="#finance">Finance</a></li>
<li><a href="#politics">Politics</a></li>
</ul>
</nav>
</header>
<!-- Main Section -->
<aside id="left">
<h3>What's Trending</h3>
<ul>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img1.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img2.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img3.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img4.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
</ul>
</aside>
<main id="center">
<section id="main-content">
<h2>Now Thrashing</h2>
<ul>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img5.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img6.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img1.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img2.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
</ul>
</section>
</main>
<aside id="right">
<h3>Newest Thrash</h3>
<ul class>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img3.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img4.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img5.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Title</h4>
<img class="lozad" data-src="src/img/img6.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat, consectetur.</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
</ul>
</aside>
<!-- End main section -->
<main id="center">
<section id="main-content">
<h2>Now Thrashing</h2>
<ul>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img5.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img6.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img1.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
<li>
<h4>Today's Youth</h4>
<img class="lozad" data-src="src/img/img2.jpeg">
<span><em>July 4th, 2018</em></span>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem iusto debitis eveniet molestiae quos accusantium? Labore, architecto illum quae atque!</p>
<a href="#post">Read More<span class="pulse-right"> >></span></a>
</li>
</ul>
</section>
</main>
<footer id="main-footer">
<section id="mf-img">
<img class="lozad" data-src="src/img/mf-img.jpg" alt="">
</section>
<nav id="mf-nav-1">
<ul>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Careers</a></li>
<li><a href="#">Log In</a></li>
<li><a href="#">Sign Up</a></li>
</ul>
<ul>
<li><a href="#">Community</a></li>
<li><a href="#">Thrash Life</a></li>
<li><a href="#">Hashtags</a></li>
<li><a href="#">Location</a></li>
<li><a href="#">About Louisville</a></li>
</ul>
<ul>
<li><a href="#">Programming</a></li>
<li><a href="#">Bleeding Edge</a></li>
<li><a href="#">Arrow Functions</a></li>
<li><a href="#">Python</a></li>
<li><a href="#">Coding</a></li>
</ul>
</nav>
<nav id="mf-nav-2">
<ul>
<li><a href="#">News</a></li>
<li><a href="#">Tech</a></li>
<li><a href="#">Dev</a></li>
<li><a href="#">Sports</a></li>
<li><a href="#">Politics</a></li>
</ul>
</nav>
</footer>
<footer id="sub-footer">
<section class="form-wrapper">
<h5>Contact Us</h5>
<form>
<input type="text" name="Name" placeholder="Name"/>
<input type="email" name="Email" placeholder="Email"/>
<textarea type="textarea" name="Message" rows="5" cols="20"></textarea>
<a href="#">Submit</a>
</form>
</section>
<nav id="sf-nav">
<ul>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">Careers</a></li>
<li><a href="#">Log In</a></li>
<li><a href="#">Sign Up</a></li>
</ul>
</nav>
<section id="about">
<p>Thrashing Magazine</p>
<p>Copyright 2017 ©</p>
<p>Louisville, KY, USA, Earth</p>
</section>
</footer>
<!-- Scripts -->
<script type="text/javascript" src="src/js/vendor/intersection-observer.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>
<script src="js/main.min.js"></script>
<!-- End Scripts -->
</body>
</html>
|
html
|
{"remainingRequest":"/Users/apple/work/study/city33/cityPro3/node_modules/vue-loader/lib/index.js??vue-loader-options!/Users/apple/work/study/city33/cityPro3/src/views/WarningColor/index.vue?vue&type=style&index=0&id=0abddeb8&lang=scss&scoped=true&","dependencies":[{"path":"/Users/apple/work/study/city33/cityPro3/src/views/WarningColor/index.vue","mtime":1585368381011},{"path":"/Users/apple/work/study/city33/cityPro3/node_modules/css-loader/index.js","mtime":499162500000},{"path":"/Users/apple/work/study/city33/cityPro3/node_modules/vue-loader/lib/loaders/stylePostLoader.js","mtime":499162500000},{"path":"/Users/apple/work/study/city33/cityPro3/node_modules/postcss-loader/src/index.js","mtime":499162500000},{"path":"/Users/apple/work/study/city33/cityPro3/node_modules/sass-loader/lib/loader.js","mtime":499162500000},{"path":"/Users/apple/work/study/city33/cityPro3/node_modules/cache-loader/dist/cjs.js","mtime":499162500000},{"path":"/Users/apple/work/study/city33/cityPro3/node_modules/vue-loader/lib/index.js","mtime":499162500000}],"contextDependencies":[],"result":["\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n.warin-management {\n padding: 10px;\n}\n.search {\n margin-top: 20px;\n .el-input {\n width: 180px;\n }\n}\n.inputP{\n position: relative;\n}\n .input{\n position: absolute;\n top:2px;\n left: 10px;\n z-index: 999;\n }\n\n",null]}
|
json
|
# 分布式事务
## 分布式一致性
在分布式系统中,为了保证数据的高可用,通常,我们会将数据保留多个副本(replica),这些副本会放置在不同的物理的机器上。为了对用户提供正确的 CRUD 等语义,我们需要保证这些放置在不同物理机器上的副本是一致的。
为了解决这种分布式一致性问题,前人在性能和数据一致性的反反复复权衡过程中总结了许多典型的协议和算法。其中比较著名的有**二阶提交协议(Two Phase Commitment Protocol)**、**三阶提交协议(Three Phase Commitment Protocol)** 和 **Paxos 算法**。
## 分布式事务
::: tip
分布式事务是指会涉及到操作多个数据库的事务。其实就是将对同一库事务的概念扩大到了对多个库的事务。目的是为了保证分布式系统中的数据一致性。分布式事务处理的关键是必须有一种方法可以知道事务在任何地方所做的所有动作,提交或回滚事务的决定必须产生统一的结果(全部提交或全部回滚)
:::
在分布式系统中,各个节点之间在物理上相互独立,通过网络进行沟通和协调。由于存在事务机制,可以保证每个独立节点上的数据操作可以满足 ACID。但是,相互独立的节点之间无法准确的知道其他节点中的事务执行情况。所以从理论上讲,两台机器理论上无法达到一致的状态。如果想让分布式部署的多台机器中的数据保持一致性,那么就要保证在所有节点的数据写操作,要不全部都执行,要么全部的都不执行。但是,一台机器在执行本地事务的时候无法知道其他机器中的本地事务的执行结果。所以他也就不知道本次事务到底应该 commit 还是 rollback。所以,常规的解决办法就是引入一个“协调者”的组件来统一调度所有分布式节点的执行。
## XA 规范
X/Open 组织(即现在的 Open Group )定义了分布式事务处理模型。 X/Open DTP 模型( 1994 )包括应用程序( AP )、事务管理器( TM )、资源管理器( RM )、通信资源管理器( CRM )四部分。一般,常见的事务管理器( TM )是交易中间件,常见的资源管理器( RM )是数据库,常见的通信资源管理器( CRM )是消息中间件。 通常把一个数据库内部的事务处理,如对多个表的操作,作为本地事务看待。数据库的事务处理对象是本地事务,而分布式事务处理的对象是全局事务。 所谓全局事务,是指分布式事务处理环境中,多个数据库可能需要共同完成一个工作,这个工作即是一个全局事务,例如,一个事务中可能更新几个不同的数据库。对数据库的操作发生在系统的各处但必须全部被提交或回滚。此时一个数据库对自己内部所做操作的提交不仅依赖本身操作是否成功,还要依赖与全局事务相关的其它数据库的操作是否成功,如果任一数据库的任一操作失败,则参与此事务的所有数据库所做的所有操作都必须回滚。 一般情况下,某一数据库无法知道其它数据库在做什么,因此,在一个 DTP 环境中,交易中间件是必需的,由它通知和协调相关数据库的提交或回滚。而一个数据库只将其自己所做的操作(可恢复)影射到全局事务中。
::: tip
XA 就是 X/Open DTP 定义的交易中间件与数据库之间的接口规范(即接口函数),交易中间件用它来通知数据库事务的开始、结束以及提交、回滚等。 XA 接口函数由数据库厂商提供。
:::
二阶提交协议和三阶提交协议就是根据这一思想衍生出来的。可以说二阶段提交其实就是实现 XA 分布式事务的关键(确切地说:两阶段提交主要保证了分布式事务的原子性:即所有结点要么全做要么全不做)
### 2PC
::: tip
二阶段提交(Two-phaseCommit)是指,在计算机网络以及数据库领域内,为了使基于分布式系统架构下的所有节点在进行事务提交时保持一致性而设计的一种算法(Algorithm)。通常,二阶段提交也被称为是一种协议(Protocol))。在分布式系统中,每个节点虽然可以知晓自己的操作时成功或者失败,却无法知道其他节点的操作的成功或失败。当一个事务跨越多个节点时,为了保持事务的ACID特性,需要引入一个作为协调者的组件来统一掌控所有节点(称作参与者)的操作结果并最终指示这些节点是否要把操作结果进行真正的提交(比如将更新后的数据写入磁盘等等)。因此,**二阶段提交的算法思路可以概括为:参与者将操作成败通知协调者,再由协调者根据所有参与者的反馈情报决定各参与者是否要提交操作还是中止操作**。
:::
所谓的两个阶段是指:第一阶段:**准备阶段(投票阶段)** 和第二阶段:**提交阶段(执行阶段)**。
### 准备阶段
事务协调者(事务管理器)给每个参与者(资源管理器)发送 Prepare 消息,每个参与者要么直接返回失败(如权限验证失败),要么在本地执行事务,写本地的 redo 和 undo 日志,但不提交,到达一种“万事俱备,只欠东风”的状态。
可以进一步将准备阶段分为以下三个步骤:
1. 协调者节点向所有参与者节点询问是否可以执行提交操作(vote),并开始等待各参与者节点的响应。
2. 参与者节点执行询问发起为止的所有事务操作,并将 Undo 信息和 Redo 信息写入日志。(注意:若成功这里其实每个参与者已经执行了事务操作)
3. 各参与者节点响应协调者节点发起的询问。如果参与者节点的事务操作实际执行成功,则它返回一个”同意”消息;如果参与者节点的事务操作实际执行失败,则它返回一个”中止”消息。
### 提交阶段
如果协调者收到了参与者的失败消息或者超时,直接给每个参与者发送回滚( Rollback )消息;否则,发送提交( Commit )消息;参与者根据协调者的指令执行提交或者回滚操作,释放所有事务处理过程中使用的锁资源。(注意:必须在最后阶段释放锁资源)
接下来分两种情况分别讨论提交阶段的过程。
当协调者节点从所有参与者节点获得的相应消息都为”同意”时:

1. 协调者节点向所有参与者节点发出”正式提交( commit )”的请求。
2. 参与者节点正式完成操作,并释放在整个事务期间内占用的资源。
3. 参与者节点向协调者节点发送”完成”消息。
4. 协调者节点受到所有参与者节点反馈的”完成”消息后,完成事务。
如果任一参与者节点在第一阶段返回的响应消息为”中止”,或者 协调者节点在第一阶段的询问超时之前无法获取所有参与者节点的响应消息时:

1. 协调者节点向所有参与者节点发出”回滚操作( rollback )”的请求。
2. 参与者节点利用之前写入的 Undo 信息执行回滚,并释放在整个事务期间内占用的资源。
3. 参与者节点向协调者节点发送”回滚完成”消息。
4. 协调者节点受到所有参与者节点反馈的”回滚完成”消息后,取消事务。
**不管最后结果如何,第二阶段都会结束当前事务。**
二阶段提交看起来确实能够提供原子性的操作,但是不幸的事,二阶段提交还是有几个**缺点**的:
1. **同步阻塞问题**:执行过程中,所有参与节点都是事务阻塞型的。当参与者占有公共资源时,其他第三方节点访问公共资源不得不处于阻塞状态。
2. **单点故障**:由于协调者的重要性,一旦协调者发生故障。参与者会一直阻塞下去。尤其在第二阶段,协调者发生故障,那么所有的参与者还都处于锁定事务资源的状态中,而无法继续完成事务操作。(如果是协调者挂掉,可以重新选举一个协调者,但是无法解决因为协调者宕机导致的参与者处于阻塞状态的问题)
3. **数据不一致**:在二阶段提交的阶段二中,当协调者向参与者发送 commit 请求之后,发生了局部网络异常或者在发送 commit 请求过程中协调者发生了故障,这回导致只有一部分参与者接受到了 commit 请求。而在这部分参与者接到 commit 请求之后就会执行 commit 操作。但是其他部分未接到 commit 请求的机器则无法执行事务提交。于是整个分布式系统便出现了数据部一致性的现象。
4. 二阶段无法解决的问题:协调者再发出 commit 消息之后宕机,而唯一接收到这条消息的参与者同时也宕机了。那么即使协调者通过选举协议产生了新的协调者,这条事务的状态也是不确定的,没人知道事务是否被已经提交。
由于二阶段提交存在着诸如同步阻塞、单点问题、脑裂等缺陷,所以,研究者们在二阶段提交的基础上做了改进,提出了三阶段提交。
### 3PC
::: tip
三阶段提交(Three-phase commit),也叫三阶段提交协议(Three-phase commit protocol),是二阶段提交(2PC)的改进版本。
:::

与两阶段提交不同的是,三阶段提交有两个改动点。
引入超时机制。同时在协调者和参与者中都引入超时机制。
在第一阶段和第二阶段中插入一个准备阶段。保证了在最后提交阶段之前各参与节点的状态是一致的。
也就是说,除了引入超时机制之外,3PC 把 2PC 的准备阶段再次一分为二,这样三阶段提交就有 CanCommit、PreCommit、DoCommit 三个阶段。
### CanCommit 阶段
3PC 的 CanCommit 阶段其实和 2PC 的准备阶段很像。协调者向参与者发送 commit 请求,参与者如果可以提交就返回 Yes 响应,否则返回 No 响应。
1. **事务询问**:协调者向参与者发送CanCommit请求。询问是否可以执行事务提交操作。然后开始等待参与者的响应。
2. **响应反馈**:参与者接到CanCommit请求之后,正常情况下,如果其自身认为可以顺利执行事务,则返回Yes响应,并进入预备状态。否则反馈No
### PreCommit 阶段
协调者根据参与者的反应情况来决定是否可以记性事务的 PreCommit 操作。根据响应情况,有以下两种可能。
1. **假如协调者从所有的参与者获得的反馈都是 Yes 响应,那么就会执行事务的预执行。**
- 发送预提交请求:协调者向参与者发送 PreCommit 请求,并进入 Prepared 阶段。
- 事务预提交:参与者接收到 PreCommit 请求后,会执行事务操作,并将 undo 和 redo 信息记录到事务日志中。
- 响应反馈:如果参与者成功的执行了事务操作,则返回 ACK 响应,同时开始等待最终指令。
2. **假如有任何一个参与者向协调者发送了 No 响应,或者等待超时之后,协调者都没有接到参与者的响应,那么就执行事务的中断。**
- 发送中断请求:协调者向所有参与者发送 abort 请求。
- 中断事务:参与者收到来自协调者的 abort 请求之后(或超时之后,仍未收到协调者的请求),执行事务的中断。
### doCommit 阶段
该阶段进行真正的事务提交,也可以分为以下两种情况。
1. **执行提交**
- 发送提交请求:协调接收到参与者发送的 ACK 响应,那么他将从预提交状态进入到提交状态。并向所有参与者发送 doCommit 请求。
- 事务提交:参与者接收到 doCommit 请求之后,执行正式的事务提交。并在完成事务提交之后释放所有事务资源。
- 响应反馈:事务提交完之后,向协调者发送 ACK 响应。
- 完成事务:协调者接收到所有参与者的 ACK 响应之后,完成事务。
2. **中断事务**
协调者没有接收到参与者发送的 ACK 响应(可能是接受者发送的不是 ACK 响应,也可能响应超时),那么就会执行中断事务。
- 发送中断请求:协调者向所有参与者发送 abort 请求
- 事务回滚:参与者接收到 abort 请求之后,利用其在阶段二记录的 undo 信息来执行事务的回滚操作,并在完成回滚之后释放所有的事务资源。
- 反馈结果:参与者完成事务回滚之后,向协调者发送 ACK 消息
- 中断事务:协调者接收到参与者反馈的ACK消息之后,执行事务的中断。
::: tip
在 doCommit 阶段,如果参与者无法及时接收到来自协调者的 doCommit 或者 abort 请求时,会在等待超时之后,会继续进行事务的提交。(其实这个应该是基于概率来决定的,当进入第三阶段时,说明参与者在第二阶段已经收到了 PreCommit 请求,那么协调者产生 PreCommit 请求的前提条件是他在第二阶段开始之前,收到所有参与者的 CanCommit 响应都是 Yes。(一旦参与者收到了 PreCommit,意味他知道大家其实都同意修改了)所以,一句话概括就是,当进入第三阶段时,由于网络超时等原因,虽然参与者没有收到 commit 或者 abort 响应,但是他有理由相信:成功提交的几率很大。)
:::
## 2PC 与 3PC 的区别
相对于 2PC,3PC 主要解决的单点故障问题,并减少阻塞,因为一旦参与者无法及时收到来自协调者的信息之后,他会默认执行 commit。而不会一直持有事务资源并处于阻塞状态。但是这种机制也会导致数据一致性问题,因为,由于网络原因,协调者发送的 abort 响应没有及时被参与者接收到,那么参与者在等待超时之后执行了 commit 操作。这样就和其他接到 abort 命令并执行回滚的参与者之间存在数据不一致的情况。
|
markdown
|
<reponame>davidbrownell/DavidBrownell_DecisionEngine<filename>src/DecisionEngine/ConstrainedResource/CalculatedWorkingSystem.cpp
/////////////////////////////////////////////////////////////////////////
///
/// \file CalculatedWorkingSystem.cpp
/// \brief See CalculatedWorkingSystem.h
///
/// \author <NAME> <<EMAIL>>
/// \date 2020-06-24 15:36:38
///
/// \note
///
/// \bug
///
/////////////////////////////////////////////////////////////////////////
///
/// \attention
/// Copyright <NAME> 2020-21
/// Distributed under the Boost Software License, Version 1.0. See
/// accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt.
///
/////////////////////////////////////////////////////////////////////////
#include "CalculatedWorkingSystem.h"
namespace DecisionEngine {
namespace ConstrainedResource {
// ----------------------------------------------------------------------
// |
// | CalculatedWorkingSystem
// |
// ----------------------------------------------------------------------
CalculatedWorkingSystem::CalculatedWorkingSystem(WorkingSystem::ImmutableStatePtr pImmutableState, WorkingSystem::TransitionState transition, Score score, Index index) :
Core::Components::CalculatedWorkingSystem(std::move(score), std::move(index)),
_pImmutableState(
std::move(
[&pImmutableState](void) -> WorkingSystem::ImmutableStatePtr & {
ENSURE_ARGUMENT(pImmutableState);
return pImmutableState;
}()
)
),
_transitionState(std::move(transition))
{}
std::string CalculatedWorkingSystem::ToString(void) const /*override*/ {
return boost::str(
boost::format("ConstrainedResource::CalculatedWorkingSystem(%1%,%2%)")
% GetScore().ToString()
% GetIndex().ToString()
);
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
CalculatedWorkingSystem::WorkingSystemPtr CalculatedWorkingSystem::CommitImpl(Score score, Index index) /*override*/ {
return std::make_shared<WorkingSystem>(
std::move(_pImmutableState),
std::move(_transitionState),
std::move(score),
std::move(index)
);
}
} // namespace ConstrainedResource
} // namespace DecisionEngine
SERIALIZATION_POLYMORPHIC_DEFINE(DecisionEngine::ConstrainedResource::CalculatedWorkingSystem);
|
cpp
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jorphan.collections;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
/**
* Use this class to store database-like data. This class uses rows and columns
* to organize its data. It has some convenience methods that allow fast loading
* and retrieval of the data into and out of string arrays. It is also handy for
* reading CSV files.
*
* WARNING: the class assumes that column names are unique, but does not enforce this.
*
*/
public class Data implements Serializable {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final long serialVersionUID = 240L;
private final Map<String, List<Object>> data;
private List<String> header;
// saves current position in data List
private int currentPos, size;
/**
* Constructor - takes no arguments.
*/
public Data() {
header = new ArrayList<String>();
data = new HashMap<String, List<Object>>();
currentPos = -1;
size = currentPos + 1;
}
/**
* Replaces the given header name with a new header name.
*
* @param oldHeader
* Old header name.
* @param newHeader
* New header name.
*/
public void replaceHeader(String oldHeader, String newHeader) {
List<Object> tempList;
int index = header.indexOf(oldHeader);
header.set(index, newHeader);
tempList = data.remove(oldHeader);
data.put(newHeader, tempList);
}
/**
* Adds the rows of the given Data object to this Data object.
*
* @param d
* data object to be appended to this one
*/
public void append(Data d) {
boolean valid = true;
String[] headers = getHeaders();
String[] dHeaders = d.getHeaders();
if (headers.length != dHeaders.length) {
valid = false;
} else {
for (int count = 0; count < dHeaders.length; count++) {
if (!header.contains(dHeaders[count])) {
valid = false;
break;
}
}
}
if (valid) {
currentPos = size;
d.reset();
while (d.next()) {
for (int count = 0; count < headers.length; count++) {
addColumnValue(headers[count], d.getColumnValue(headers[count]));
}
}
}
}
/**
* Get the number of the current row.
*
* @return integer representing the current row
*/
public int getCurrentPos() {
return currentPos;
}
/**
* Removes the current row.
*/
public void removeRow() {
List<Object> tempList;
Iterator<String> it = data.keySet().iterator();
log.debug("removing row, size = " + size);
if (currentPos > -1 && currentPos < size) {
log.debug("got to here");
while (it.hasNext()) {
tempList = data.get(it.next());
tempList.remove(currentPos);
}
if (currentPos > 0) {
currentPos--;
}
size--;
}
}
public void removeRow(int index) {
log.debug("Removing row: " + index);
if (index < size) {
setCurrentPos(index);
log.debug("Setting currentpos to " + index);
removeRow();
}
}
public void addRow() {
String[] headers = getHeaders();
List<Object> tempList = new ArrayList<Object>();
for (int i = 0; i < headers.length; i++) {
if ((tempList = data.get(header.get(i))) == null) {
tempList = new ArrayList<Object>();
data.put(headers[i], tempList);
}
tempList.add("");
}
size = tempList.size();
setCurrentPos(size - 1);
}
/**
* Sets the current pos. If value sent to method is not a valid number, the
* current position is set to one higher than the maximum.
*
* @param r
* position to set to.
*/
public void setCurrentPos(int r) {
currentPos = r;
}
/**
* Sorts the data using a given row as the sorting criteria. A boolean value
* indicates whether to sort ascending or descending.
*
* @param column
* name of column to use as sorting criteria.
* @param asc
* boolean value indicating whether to sort ascending or
* descending. True for asc, false for desc. Currently this
* feature is not enabled and all sorts are asc.
*/
public void sort(String column, boolean asc) {
sortData(column, 0, size);
}
private void swapRows(int row1, int row2) {
List<Object> temp;
Object o;
Iterator<String> it = data.keySet().iterator();
while (it.hasNext()) {
temp = data.get(it.next());
o = temp.get(row1);
temp.set(row1, temp.get(row2));
temp.set(row2, o);
}
}
/**
* Private method that implements the quicksort algorithm to sort the rows
* of the Data object.
*
* @param column
* name of column to use as sorting criteria.
* @param start
* starting index (for quicksort algorithm).
* @param end
* ending index (for quicksort algorithm).
*/
private void sortData(String column, int start, int end) {
int x = start, y = end - 1;
String basis = ((List<?>) data.get(column)).get((x + y) / 2).toString();
if (x == y) {
return;
}
while (x <= y) {
while (x < end && ((List<?>) data.get(column)).get(x).toString().compareTo(basis) < 0) {
x++;
}
while (y >= (start - 1) && ((List<?>) data.get(column)).get(y).toString().compareTo(basis) > 0) {
y--;
}
if (x <= y) {
swapRows(x, y);
x++;
y--;
}
}
if (x == y) {
x++;
}
y = end - x;
if (x > 0) {
sortData(column, start, x);
}
if (y > 0) {
sortData(column, x, end);
}
}
/**
* Gets the number of rows in the Data object.
*
* @return number of rows in Data object.
*/
public int size() {
return size;
} // end method
/**
* Adds a value into the Data set at the current row, using a column name to
* find the column in which to insert the new value.
*
* @param column
* the name of the column to set.
* @param value
* value to set into column.
*/
public void addColumnValue(String column, Object value) {
List<Object> tempList;
if ((tempList = data.get(column)) == null) {
tempList = new ArrayList<Object>();
data.put(column, tempList);
}
int s = tempList.size();
if (currentPos == -1) {
currentPos = size;
}
if (currentPos >= size) {
size = currentPos + 1;
}
while (currentPos > s) {
s++;
tempList.add(null);
}
if (currentPos == s) {
tempList.add(value);
} else {
tempList.set(currentPos, value);
}
}
/**
* Returns the row number where a certain value is.
*
* @param column
* column to be searched for value.
* @param value
* object in Search of.
* @return row # where value exists.
*/
public int findValue(String column, Object value) {
return data.get(column).indexOf(value);
}
/**
* Sets the value in the Data set at the current row, using a column name to
* find the column in which to insert the new value.
*
* @param column
* the name of the column to set.
* @param value
* value to set into column.
*/
public void setColumnValue(String column, Object value) {
List<Object> tempList;
if ((tempList = data.get(column)) == null) {
tempList = new ArrayList<Object>();
data.put(column, tempList);
}
if (currentPos == -1) {
currentPos = 0;
}
if (currentPos >= size) {
size++;
tempList.add(value);
} else if (currentPos >= tempList.size()) {
tempList.add(value);
} else {
tempList.set(currentPos, value);
}
}
/**
* Checks to see if a column exists in the Data object.
*
* @param column
* Name of column header to check for.
* @return True or False depending on whether the column exists.
*/
public boolean hasHeader(String column) {
return data.containsKey(column);
}
/**
* Sets the current position of the Data set to the next row.
*
* @return True if there is another row. False if there are no more rows.
*/
public boolean next() {
return (++currentPos < size);
}
/**
* Gets a Data object from a ResultSet.
*
* @param rs
* ResultSet passed in from a database query
* @return a Data object
* @throws java.sql.SQLException
*/
public static Data getDataFromResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
Data data = new Data();
int numColumns = meta.getColumnCount();
String[] dbCols = new String[numColumns];
for (int i = 0; i < numColumns; i++) {
dbCols[i] = meta.getColumnName(i + 1);
data.addHeader(dbCols[i]);
}
while (rs.next()) {
data.next();
for (int i = 0; i < numColumns; i++) {
Object o = rs.getObject(i + 1);
if (o instanceof byte[]) {
o = new String((byte[]) o); // TODO - charset?
}
data.addColumnValue(dbCols[i], o);
}
}
return data;
}
/**
* Sets the current position of the Data set to the previous row.
*
* @return True if there is another row. False if there are no more rows.
*/
public boolean previous() {
return (--currentPos >= 0);
}
/**
* Resets the current position of the data set to just before the first
* element.
*/
public void reset() {
currentPos = -1;
}
/**
* Gets the value in the current row of the given column.
*
* @param column
* name of the column.
* @return an Object which holds the value of the column.
*/
public Object getColumnValue(String column) {
try {
if (currentPos < size) {
return ((List<?>) data.get(column)).get(currentPos);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
/**
* Gets the value in the current row of the given column.
*
* @param column
* index of the column (starts at 0).
* @return an Object which holds the value of the column.
*/
public Object getColumnValue(int column) {
String columnName = header.get(column);
try {
if (currentPos < size) {
return ((List<?>) data.get(columnName)).get(currentPos);
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
public Object getColumnValue(int column, int row) {
setCurrentPos(row);
return getColumnValue(column);
}
public void removeColumn(int col) {
String columnName = header.get(col);
data.remove(columnName);
header.remove(columnName);
}
/**
* Sets the headers for the data set. Each header represents a column of
* data. Each row's data can be gotten with the column header name, which
* will always be a string.
*
* @param h
* array of strings representing the column headers.
* these must be distinct - duplicates will cause incorrect behaviour
*/
public void setHeaders(String[] h) {
int x = 0;
header = new ArrayList<String>(h.length);
for (x = 0; x < h.length; x++) {
header.add(h[x]);
data.put(h[x], new ArrayList<Object>());
}
}
/**
* Returns a String array of the column headers.
*
* @return array of strings of the column headers.
*/
public String[] getHeaders() {
String[] r = new String[header.size()];
if (r.length > 0) {
r = header.toArray(r);
}
return r;
}
public int getHeaderCount(){
return header.size();
}
/**
* This method will retrieve every entry in a certain column. It returns an
* array of Objects from the column.
*
* @param columnName
* name of the column.
* @return array of Objects representing the data.
*/
public List<Object> getColumnAsObjectArray(String columnName) {
return data.get(columnName);
}
/**
* This method will retrieve every entry in a certain column. It returns an
* array of strings from the column. Even if the data are not strings, they
* will be returned as strings in this method.
*
* @param columnName
* name of the column.
* @return array of Strings representing the data.
*/
public String[] getColumn(String columnName) {
String[] returnValue;
List<?> temp = data.get(columnName);
if (temp != null) {
returnValue = new String[temp.size()];
int index = 0;
for (Object o : temp) {
if (o != null) {
if (o instanceof String) {
returnValue[index++] = (String) o;
} else {
returnValue[index++] = o.toString();
}
}
}
} else {
returnValue = new String[0];
}
return returnValue;
}
/**
* Use this method to set the entire data set. It takes an array of strings.
* It uses the first row as the headers, and the next rows as the data
* elements. Delimiter represents the delimiting character(s) that separate
* each item in a data row.
*
* @param contents
* array of strings, the first element is a list of the column
* headers, the next elements each represent a single row of
* data.
* @param delimiter
* the delimiter character that separates columns within the
* string array.
*/
public void setData(String[] contents, String delimiter) {
setHeaders(JOrphanUtils.split(contents[0], delimiter));
int x = 1;
while (x < contents.length) {
setLine(JOrphanUtils.split(contents[x++], delimiter));
}
}
/*
* Deletes a header from the Data object. Takes the column name as input. It
* will delete the entire column.
*
* public void deleteHeader(String s) {
* }
*/
/**
* Sets the data for every row in the column.
*/
public void setColumnData(String colName, Object value) {
List<Object> list = this.getColumnAsObjectArray(colName);
while (list.size() < size()) {
list.add(value);
}
}
public void setColumnData(int col, List<?> data) {
reset();
Iterator<?> iter = data.iterator();
String columnName = header.get(col);
while (iter.hasNext()) {
next();
setColumnValue(columnName, iter.next());
}
}
/**
* Adds a header name to the Data object.
*
* @param s
* name of header.
*/
public void addHeader(String s) {
header.add(s);
data.put(s, new ArrayList<Object>(Math.max(size(), 100)));
}
/**
* Sets a row of data using an array of strings as input. Each value in the
* array represents a column's value in that row. Assumes the order will be
* the same order in which the headers were added to the data set.
*
* @param line
* array of strings representing column values.
*/
public void setLine(String[] line) {
List<Object> tempList;
String[] h = getHeaders();
for (int count = 0; count < h.length; count++) {
tempList = data.get(h[count]);
if (count < line.length && line[count].length() > 0) {
tempList.add(line[count]);
} else {
tempList.add("N/A");
}
}
size++;
}
/**
* Sets a row of data using an array of strings as input. Each value in the
* array represents a column's value in that row. Assumes the order will be
* the same order in which the headers were added to the data set.
*
* @param line
* array of strings representing column values.
* @param deflt
* default value to be placed in data if line is not as long as
* headers.
*/
public void setLine(String[] line, String deflt) {
List<Object> tempList;
String[] h = getHeaders();
for (int count = 0; count < h.length; count++) {
tempList = data.get(h[count]);
if (count < line.length && line[count].length() > 0) {
tempList.add(line[count]);
} else {
tempList.add(deflt);
}
}
size++;
}
/**
* Returns all the data in the Data set as an array of strings. Each array
* gives a row of data, each column separated by tabs.
*
* @return array of strings.
*/
public String[] getDataAsText() {
StringBuilder temp = new StringBuilder("");
String[] line = new String[size + 1];
String[] elements = getHeaders();
for (int count = 0; count < elements.length; count++) {
temp.append(elements[count]);
if (count + 1 < elements.length) {
temp.append("\t");
}
}
line[0] = temp.toString();
reset();
int index = 1;
temp = new StringBuilder();
while (next()) {
temp.setLength(0);
for (int count = 0; count < elements.length; count++) {
temp.append(getColumnValue(count));
if (count + 1 < elements.length) {
temp.append("\t");
}
}
line[index++] = temp.toString();
}
return line;
}
@Override
public String toString() {
String[] contents = getDataAsText();
StringBuilder sb = new StringBuilder();
boolean first = true;
for (int x = 0; x < contents.length; x++) {
if (!first) {
sb.append("\n");
} else {
first = false;
}
sb.append(contents[x]);
}
return sb.toString();
}
}
|
java
|
<gh_stars>1-10
/*
Copyright 2019-2020 vChain, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package immuc
import (
c "github.com/codenotary/immudb/cmd/helper"
"github.com/codenotary/immudb/pkg/client"
"github.com/spf13/viper"
)
type immuc struct {
ImmuClient client.ImmuClient
passwordReader c.PasswordReader
valueOnly bool
options *client.Options
isLoggedin bool
}
// Client ...
type Client interface {
Connect(args []string) error
Disconnect(args []string) error
CurrentRoot(args []string) (string, error)
GetByIndex(args []string) (string, error)
GetKey(args []string) (string, error)
RawSafeGetKey(args []string) (string, error)
SafeGetKey(args []string) (string, error)
GetRawBySafeIndex(args []string) (string, error)
Login(args []string) (string, error)
Logout(args []string) (string, error)
History(args []string) (string, error)
HealthCheck(args []string) (string, error)
Reference(args []string) (string, error)
SafeReference(args []string) (string, error)
ZScan(args []string) (string, error)
IScan(args []string) (string, error)
Scan(args []string) (string, error)
Count(args []string) (string, error)
RawSafeSet(args []string) (string, error)
Set(args []string) (string, error)
SafeSet(args []string) (string, error)
ZAdd(args []string) (string, error)
SafeZAdd(args []string) (string, error)
Consistency(args []string) (string, error)
Inclusion(args []string) (string, error)
ValueOnly() bool
SetValueOnly(v bool)
CreateDatabase(args []string) (string, error)
UseDatabase(args []string) (string, error)
UserOperations(args []string) (string, error)
}
// Init ...
func Init() (Client, error) {
ic := new(immuc)
ic.passwordReader = c.DefaultPasswordReader
return ic, nil
}
func (i *immuc) Connect(args []string) error {
i.options = options()
len, err := client.ReadFileFromUserHomeDir(i.options.TokenFileName)
if err != nil || len == "" {
i.options.Auth = false
} else {
i.options.Auth = true
}
if i.ImmuClient, err = client.NewImmuClient(i.options); err != nil || i.ImmuClient == nil {
return err
}
i.valueOnly = viper.GetBool("value-only")
return nil
}
func (i *immuc) Disconnect(args []string) error {
if err := i.ImmuClient.Disconnect(); err != nil {
return err
}
return nil
}
func options() *client.Options {
options := client.DefaultOptions().
WithPort(viper.GetInt("immudb-port")).
WithAddress(viper.GetString("immudb-address")).
WithTokenFileName(viper.GetString("tokenfile")).
WithMTLs(viper.GetBool("mtls"))
if viper.GetBool("mtls") {
// todo https://golang.org/src/crypto/x509/root_linux.go
options.MTLsOptions = client.DefaultMTLsOptions().
WithServername(viper.GetString("servername")).
WithCertificate(viper.GetString("certificate")).
WithPkey(viper.GetString("pkey")).
WithClientCAs(viper.GetString("clientcas"))
}
return options
}
func (i *immuc) ValueOnly() bool {
return i.isLoggedin
}
func (i *immuc) SetValueOnly(v bool) {
i.isLoggedin = v
return
}
|
go
|
<filename>app/web/store/app/getters.js
'use strict'
const getters = {}
export default getters
|
javascript
|
Australia trail by 214 runs with nine wickets in hand, going into Day Three of the third Test against Sri Lanka.
Rangana Herath, Dilruwan Perera and Lakshan Sandakan have tried their best to get a breakthrough, but they have failed. They will look to get a couple of quick wickets in the first session and look to put the opposition on the back foot early on. Marsh, who has an average of over 80 in the subcontinent wil look to make this a big innings and help Australia avoid the whitewash.
|
english
|
.background-container {
scroll-behavior: smooth;
background: #343a40;
min-height: 100vh;
height: fit-content;
}
|
css
|
Convertibles were all the rage back in the 1950s (thanks to tailfins and the Corvette) and in the early 2000s (thanks to Microsoft and Sony). In the 2000s, however, we saw convertibles in the form of laptops that could twist and turn themselves into tablets. The result, usually, was a not-very-good-laptop folded into a not-very-good tablet.
That’s what makes the Yoga special. This 13-inch laptop is as plain as can be – it has just two USB ports and an SD card slot – but becomes much more usable when you realize the various configurations you can bend it into. For example, as a laptop the screen stays straight up and there is a small central Windows button that you can either press or ignore under the screen bezel. You can also fold the laptop in half along one edge, essentially tuning off the keyboard and making the screen one big tablet. Finally, you can fold the Yoga into a tent, allowing you some modicum of control over the laptop via the keyboard or allowing you and another user to view the screen head-on.
To be fair, the “folding” features are more of a gimmick than anything else. The vast majority of the time you’ll be using this in either standard laptop mode or tablet mode. However, unlike the Microsoft Surface, you don’t have to worry about the screen flopping over at inopportune moments, which is a huge plus.
The Yoga can be rightly termed the perfect Windows 8 machine. Touchscreen access was surprisingly smooth and responsive but it wasn’t mandatory. This is a handsome, cleverly designed laptop that works as both a keyboard-based and touch device. Performance-wise, however, you’re going to take a bit of a hit on this device when compared to similar i5 devices.
They Yoga 13 hit a Geekbench score of 4,664, which is low. The i5 MacBook Air, for example, gets about 5,000 other Core i5 laptops can hover at about 8,000 depending on the machine. The laptop lasted for 5 hours of standard use. The Core i5 in this model was enough for most work thrown at it but it’s still considerably underpowered. Other users I talked to mentioned some latency issues with the trackpad although I didn’t experience them during use.
That said, I’m loath to ding the laptop on performance simply because Lenovo did something very unique with their laptop and made something that I’d actually carry. The goal of these reviews is to show some of the most unique and usable laptops available now, not the latest and greatest in terms of chipsets and processors. In terms of speeds and feeds the Yoga 13 does not shine. However, when it comes down to usability and class, the Yoga 13 is a real contender.
Who is it for?
Yes. Photographers, artists, and media types will love the big, bright screen and the unique “bendable” spine makes it easy to share the screen with multiple users or flip it over to show off a snapshot or sketch. While it’s not exactly a Wacom digitizer – you basically get a capacitive touchscreen that will respond to simpler, passive styli – this laptop is definitely something you can get a little work done on.
I would worry, however, about the limitations of the i5 processor and the on-board graphics. I wouldn’t recommend, say, rendering video or handling massive RAW files. Think of this as a showcase machine, designed to display your work after it is complete.
Yes. The Yoga is almost custom-built for salesmen and business folk. Want to get a point across? Fold this puppy up and treat it like a mini-whiteboard. Want to give a presentation? Lay it out flat like a tablet and swipe through the slides. Finally, when you have a bit of alone time and need a laptop, it’s right there and ready to go. If you’re running a Windows shop and need something that can act as both a tablet and a PC, this is probably your best bet right now. As an exploration of the Windows 8 form, this thing is great.
No. I’m not certain that this is the right laptop for a coder. It’s definitely a cool idea but the value intrinsic in the folding hinge is lost on folks who probably need the machine to act as a primary typing device. I’d recommend looking at this thing in terms of whether or not you’d use the touch features on a daily basis and make your decision that way.
The Yoga is a gimmick, to be sure. However, I think it does a good enough job at being a laptop and a tablet that the interstitial positions don’t matter as much. The Yoga 13 is everything the Surface was supposed to be and, although I do enjoy the Surface Pro, the Yoga is a superior experience.
|
english
|
export class MongoStoreConfig {
port: number = 500
mongodb: {
url: string
database: string
}
verbose?: boolean = false
}
|
typescript
|
<gh_stars>1-10
---
title: RebaseTaskComplete
manager: soliver
ms.date: 03/09/2015
ms.audience: Developer
ms.topic: overview
ms.localizationpriority: medium
ms.assetid: 2de5c77c-3fac-cfb6-3719-68df4013cf11
description: 报告约会的重做目标完成情况。
ms.openlocfilehash: 49061cf21f4a6ffd3218bac2470a1afc6e2ebf81
ms.sourcegitcommit: a1d9041c20256616c9c183f7d1049142a7ac6991
ms.translationtype: MT
ms.contentlocale: zh-CN
ms.lasthandoff: 09/24/2021
ms.locfileid: "59614330"
---
# <a name="rebasetaskcomplete"></a>RebaseTaskComplete
报告约会的重做目标完成情况。
## <a name="quick-info"></a>快速信息
|||
|:-----|:-----|
|标头文件: <br/> |tzmovelib.h <br/> |
|实现者: <br/> |MAPI 客户端应用程序 <br/> |
|调用者: <br/> |Outlook重做对象 <br/> |
|指针类型: <br/> |tzmovelib.h 中定义的 **PFNREBASETASKCOMPLETE** <br/> |
```cpp
void STDAPICALLTYPE RebaseTaskComplete(
ULONG ulRowIndex,
const SRow* pRowCur,
HRESULT hrResult,
BOOL fModified,
BOOL fSentUpdate,
const MAPIERROR* pError);
```
## <a name="parameters"></a>参数
_ulRowIndex_
> [in]已处理的行。 此索引引用传递到 [IOlkApptRebaser::BeginRebaseAppointments](iolkapptrebaser-beginrebaseappointments.md)的 **[SRowSet](https://msdn.microsoft.com/library/7e3761be-afd6-46cb-9a08-25e9016c1241%28Office.15%29.aspx)** 结构。
_pRowCur_
> in] 指向描述已处理项目的 **[SRow](https://msdn.microsoft.com/library/369c2d5c-8c2b-4314-9cb2-aaa89580aa2b%28Office.15%29.aspx)** 结构的指针。
_hrResult_
> [in]一 **个 HRESULT,** 指示重做basing操作的结果。
_fModified_
> [in]指定项目是否已修改。
_fSentUpdate_
> [in]指定是否发送会议更新消息。
_pError_
> [in]指向带扩展错误信息的 **MAPIERROR** 结构的指针。
## <a name="return-values"></a>返回值
如果该调用成功,则返回 S_OK否则为一个错误代码。
## <a name="remarks"></a>说明
使用 [IOlkApptRebaser](iolkapptrebaser.md) 接口的 MAPI 客户端应用程序实现此函数以跟踪项目更新的完成情况。
## <a name="see-also"></a>另请参阅
- [有关重定基址日历以编程方式为夏时制](about-rebasing-calendars-programmatically-for-daylight-saving-time.md)
|
markdown
|
Double side ascendable design equals to high productivity and operation flexibility, ideal for narrow working space and multiple point of access.
Provides large tools/ material handing especially handy for warehousing and household general applications.
Heavy duty spreader is employed to guarantee high level of stability and safety.
Natural anodized body for durability and presentable appearance.
"Corrugated" Shape design step adds extra strength for safer ascending and descending.
Ensures high level of grip whenever ladder is in used.
|Delivery Fee (RM)
|
english
|
Insertion of
new section 57D in Guj. I of 1970.
No deduction at source.
Validation of levy and collection of tax on specified works
GUJARAT GOVERNMENT GAZETTE. EX.. 28-3-2002
[PART V
(12) (a) If any person does not deduct an amount under sub-section (3) or after deducting the amount under that sub-section, fails to pay the same into the Government treasury under sub-section (7) within the time specified therein, he shall be liable to pay such penalty not exceeding twenty-five per cent. of the amount required to be deducted by him under sub-section (3) as may be imposed by the Commissioner.
(b) The Commissioner shall, for the purpose of imposing penalty under clause (a), exercise the same powers as are conferred on him under sub-sections (3) and (4) of section 46 in relation to imposing of penalty under that section.
(13) Where a person deducting the amount of tax in accordance with the provisions of sub-section (3) does not pay the amount so deducted into the Government treasury under sub-section (7) within the time specified therein, there shall be paid by such person, in addition to the penalty imposed on him under subsection (12), for the period commencing on the date of expiry of the time specified in sub-section (7) and ending on the date of payment of the amount into the Government treasury, simple interest at the rate of twenty-four per cent. during the period from 1st April, 1997 to 31st August, 2001 and thereafter at the rate of eighteen per cent. of the amount not so paid or any less amount remaining unpaid during that period.".
4. In the principal Act, after section 57C, the following section shall be added, namely :"57D. Notwithstanding anything contained in section 57B, with effect from the 1* April, 2002 tax shall not be deducted at source where payment is to be made by the State Government in case of the specified works contract of the State Government, at the time of payment of the whole or part of the specified sale price.".
5. (1) Notwithstanding anything contained in any judgement, decree or order of any court, tribunal or authority, the tax deducted, levied, assessed, reassessed or collected or purported to have been deducted, levied, assessed, reassessed or collected under the principal Act on specified sales in pursuance of a specified works contract under section 57B shall be and shall be deemed always to have been validly deducted, levied, assessed, reassessed or collected in accordance with law as if the provisions of the principal Act as amended by this Act had been in force at all material times when such tax was deducted, levied, assessed, reassessed or collected and accordingly(a) no suit, appeal, application or other proceedings shall be maintained or continued in any court or before any tribunal or authority whatsoever for the refund of the said tax,
(b) no court, tribunal or other authority shall enforce any decree or order directing refund of the said tax, and
(c) recoveries shall be made in accordance with the provisions of the principal Act as amended by this Act as if said provisions had been in force at all material times.
|
english
|
<gh_stars>1-10
import React from 'react';
import PropTypes from 'prop-types';
import { IconContext } from 'react-icons';
import { MdQueueMusic } from 'react-icons/md';
import './styles.scss';
type Props = {
id: React.Key;
title: string;
selected: boolean;
onSelect: (trackID: string | number) => void;
};
function Track(props: Props) {
return (
<div
className={['Track', props.selected && 'Track_selected']
.filter(Boolean)
.join(' ')}
onClick={() => props.onSelect(props.id)}
>
<IconContext.Provider value={{ className: 'Track__Icon' }}>
<MdQueueMusic size={30} />
</IconContext.Provider>
<div className="Track__Title">{props.title}</div>
</div>
);
}
Track.propTypes = {
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
title: PropTypes.string.isRequired,
selected: PropTypes.bool.isRequired,
onSelect: PropTypes.func.isRequired,
};
export default React.memo(Track);
|
typescript
|
Former Universal Champion Braun Strowman made a shocking return to WWE during tonight's episode of Monday Night RAW.
The last time we saw The Monster Among Men wrestle in the promotion was at WrestleMania Backlash 2021 in a Triple Threat match for the WWE Championship. The then-champion Bobby Lashley won the match to retain his title.
Strowman then fell victim to yearly budget cuts as he was released in June 2021. Since his release, Strowman has wrestled on the independent circuit under his real name Adam Scherr.
Tonight on RAW, there was an eight-men Fatal Four-way tag team match to determine the number one contender for the Undisputed WWE Tag Team Titles. The match was between The Street Profits, The New Day, Los Latharios and Alpha Academy.
Just as the match was getting interesting, we heard the roar of the Monster Among Men, and his theme song played. Strowman came out angry and destroyed all eight superstars effortlessly.
After being away from the company for over a year, Braun Strowman made his return and instantly established himself as a serious threat to the entire roster.
Strowman still has some unfinished business with United States Champion Bobby Lashley. However, the reason behind him attacking the tag teams on the RAW roster was also not revealed.
It remains to be seen how the former Universal Champion will be booked during his second stint with WWE.
Are you excited to see Braun Strowman back in WWE? Let us know in the comments section below.
|
english
|
India in general and South India in particular abounds in Saints whose main interest is serving the society through various methods. Some may deliver religious lectures while others may sing songs of these great men in their melodious voice. Others may give discourses on religious aspects specially on those whose main aim is to spread communal harmony and so on. This is not today’s story but it goes back to Vedic times, including Upanishads. Still others give discourses on Ramayana and Mahabharata emphasising the victory of the good over the evil.
This is not limited to Hinduism alone, it is enunciated in Quran and Holy Bible. The Sikhs in Gurudwaras though offer the same prayers involving religious feelings but their language may be different. The Jagadgurus of various Mutts are doing the same thing with inculcating good and religious life without malice to none.
Mahatma Gandhi in our times resorted to Satyagraha to send out the Britishers. But Gandhiji said they are our brothers and friends and we Indians have no ill-will against them. We should make the Britishers realise their mistake and allow them to go out of India and we should give them a friendly send off. Thus in ancient times people never had ill-will against anybody. But unfortunately, these things have been forgotten. It is not for the betterment of society.
Under this background the life and teachings of venerable Vasudeva Maharaj may be considered. A part of his name Vasudeva refers to Krishna of Dwapara Yuga, who played a great role in Mahabharata and helped the Pandavas to destroy the bad Kauravas. The other part of his name is Maharaj. It certainly should not be mistaken as the Maharajas with luxury, Palaces and huge wealth.
However, this venerable person is a Maharaj in his own right. Though he has no Palaces and large amount of wealth as is the case with the Maharajas, he still enjoys that fame because he is a King in religious kingdom serving the society. His full name is S. N. Vasudeva Rao and he was the third son of the couple Nagappa and Puttakka. His father Nagappa, a B. A. graduate, was a Mukhtesar (financial head) in the Mysore Palace. He lived on Tyagaraja road very close to the Sai Baba temple.
Vasudeva Rao studied in D. Banumaiah School and later got his B. Sc. degree from St. Philomena’s College, both in Mysore. Then he joined the State Bank of Mysore. He married Vijayakumari, who came from a respectable family. After serving in various banks he retired sometime in 1998.
After sometime his mind was immersed in religious life of purity and social service. Daily he used to go to the Sai Baba temple without fail. He was fasting on Thursdays, a day dedicated to Sai Baba. But was eating only prasada given at the temple. Under the guidance of the priests of the Sai Baba temple he began to read the history of Sai Baba (Sai Charita) and chanted Vishnu Sahasranama daily. In addition, he became a great devotee of Sri Raghavendraswamy who has become a legend in religious life of Karnataka and many miracles are attributed to this Holy Saint.
Even as a student he visited to Mantralaya, the Holy Abode of Sri Raghavendraswamy and sat there in trance without caring for food till he was reminded by the Mutt authorities that it was time to close the gates of the Mutt.
In 1972 he came under the influence of a Holy Avadhoota (a completely detached person from this worldly desires) and he received initiated into spiritual life (deeksha). Though he was a house holder with his wife and children, he kept himself aloof from all his desires. Whenever he was free from his normal duties, he visited Shiradi of Sai Baba fame and Ganagapura of God Dattatreya. His spiritual desire wanted to visit Mantralaya, Ramanashrama of the famous Godly mystic Saint Ramana Maharshi. He also visited the famous Ashtamutts (eight Mutts) at Udupi which was another holy place.
Further at Kyathanahalli and in Mysore city he performed the Parayana (reading the holy books many times). This he did for six years. At the instance of the Avadhootas at Mysore, he visited Sridhara Ashrama which place was sanctified by Holy Saint Sridharaswamy.
Vasudeva Rao was completely immersed in thinking about all these great saints. He had a dream in which he had the darshan (holy sight) of Saint Sridharaswamy and Raghavendraswamy and being blessed by these two saints. He was never compromising regarding the truth and he never hesitated to speak his attitude without compromising the truth. This straight-forward speaking quality made him some enemies also. But he had no time to bother about these mundane things as he was immersed in lofty ideas.
He also studied astrology and became an astrologer. He never predicted future for people taking a price but astrology was for his own personal use. He came under the influence of many astrologers and specially B. V. Raman, an astrologer of international fame. This tradition of Raman is being continued by his family member Sachidananda Babu, who regularly appears on TV. But Vasudeva Rao was predicting future and past to many persons who approached him. He did not charge for his predictions. Between 1998 and 2000 he visited many holy places in India and was happy by the darshan of various temples for Gods and Goddesses.
Such a great savant hugged the permanent sleep on 27. 8. 2007 at 2. 30 pm. Hundreds of his devotees wept for loss of this great saint. Many condolence meetings were held in Mysore, Bangalore and other places. Because of his holy life, sacrifice and good qualities, Vasudeva Rao became famous as Vasudeva Maharaj.
At the request of his devotees a basalt stone idol (black) of Vasudeva Maharaj is ready. Its weight is 67kgs and height is one and quarter feet. This idol has been carved by the expert sculptors working in the Shilpakalakendra at Mysore. At present a good and holy location is being searched to house this idol in a temple. After a suitable place is located, the temple will be built and it will become another landmark on Ramanuja road in Mysore.
In the meantime, the devotees of this great saint Vasudeva Maharaj are anxiously waiting to get blessed by this great Saint. Most people pray to God to see this temple becomes a reality soon.
The author is thankful to Vasudeva Rao’s son M. V. Nagendra Babu, SOM cartoonist, for providing information on this savant Vasudeva Maharaj.
|
english
|
Sri Lanka’s new central bank governor will hold a monetary policy meeting on Friday, a day after he takes office, a source told Reuters, as the government struggles with an economic crisis. The crisis touched off political chaos this week when the entire cabinet of President Gotabaya Rajapaksa quit, followed by the resignation of the central bank chief, Ajith Nivard Cabraal.
Nandalal Weerasinghe, a former senior deputy governor of the Central Bank of Sri Lanka who has worked with the IMF, will replace Cabraal on Thursday.
With inflation racing to the highest in a decade, hefty interest rate hikes may be looming, adding to pressure on the reeling economy and fanning further unrest.
TO READ THE FULL STORY, SUBSCRIBE NOW NOW AT JUST RS 249 A MONTH.
What you get on Business Standard Premium?
- Unlock 30+ premium stories daily hand-picked by our editors, across devices on browser and app.
- Pick your 5 favourite companies, get a daily email with all news updates on them.
- Full access to our intuitive epaper - clip, save, share articles from any device; newspaper archives from 2006.
- Preferential invites to Business Standard events.
- Curated newsletters on markets, personal finance, policy & politics, start-ups, technology, and more.
|
english
|
<reponame>Montana-Media-Arts/sonic-programming
# Sonic Programming | MART 420</br>Syllabus
Date modified: Aug-30-2021

## Table of Contents
<!-- TOC depthFrom:1 depthTo:2 withLinks:1 updateOnSave:0 orderedList:0 -->
- [Course Overview](#course-overview)
- [Professor/Instructor](#professorinstructor)
- [Description](#description)
- [Objectives & Student Learning Outcomes](#objectives--student-learning-outcomes)
- [Course Format](#course-format)
- [Pre-Requisites](#pre-requisites)
- [Books and Supplies](#books-and-supplies)
- [Course Policies](#course-policies)
- [Course Evaluation](#course-evaluation)
- [Grades](#grades)
- [Attendance](#attendance)
- [Course Workload](#course-workload)
- [SVMA, CAM, and University Policies and Information](#svma-cam-and-university-policies-and-information)
- [School of Visual and Media Arts](#school-of-visual-and-media-arts)
- [Academic Honesty, Plagiarism, and Cheating Policy](#academic-honesty-plagiarism-and-cheating-policy)
- [Sensitive Subject Matter & Censorship](#sensitive-subject-matter--censorship)
- [Be Kind](#be-kind)
- [Diversity Statement](#diversity-statement)
- [Student Support Resources](#student-support-resources)
- [COVID-19 Specific Information](#covid-19-specific-information)
- [Land Acknowledgement](#land-acknowledgement)
- [Changes to the Course](#changes-to-the-course)
- [Weekly Breakdown](#weekly-breakdown)
- [Week 1](#week-1)
- [Week 2](#week-2)
- [Week 3](#week-3)
- [Week 4](#week-4)
- [Week 5](#week-5)
- [Week 6](#week-6)
- [Week 7](#week-7)
- [Week 8](#week-8)
- [Week 9 - Crit Day #1](#week-9---crit-day-1)
- [Week 10](#week-10)
- [Week 11](#week-11)
- [Week 12](#week-12)
- [Week 13](#week-13)
- [Week 14 - Public Presentation](#week-14---public-presentation)
- [Week 15](#week-15)
<!-- /TOC -->
# Course Overview
- Name: Sonic Programming
- Course Number: MART 420.01
- CRN: 76029
- Term: Fall, 2021
- Credits: 3
- Location: McGill 127 (Mac Lab) and McGill 123 (Sound Studio)
- GitHub Link: [https://github.com/Montana-Media-Arts/sonic-programming](https://github.com/Montana-Media-Arts/sonic-programming)
- Date/Time: Fridays 10:00 am - 12:50 pm
- University Unit: [School of Visual and Media Arts (SVMA)](https://www.umt.edu/svma/), [College of the Arts and Media (CAM)](https://www.umt.edu/umarts/), [University of Montana](https://www.umt.edu)
## Professor/Instructor
- [<NAME>, PhD](http://michaelmusick.com)
- E-Mail: [<EMAIL>](mailto:<EMAIL>?subject=mart420%20Question).
- Office: McGill Hall, 232
- Office Hours:
- In-person (McG 232): Monday's noon-1pm
- Virtual via Appointment from Link: [calendly.com/michael-musick](https://calendly.com/michael-musick)
- Please select a meeting time from availability via the Calendly web service. This will then provide you with a zoom link
## Description
In _Sonic Programming_ students will learn how to utilize computer science based techniques to create, process, and distribute original sonic art and sound based work. This course will spend a majority of its time focused on the real-time creation of sonic art, as well as the application of concepts from interactive theory and interactive systems. This course combines students skills and technique in creative coding and sonic arts together.
In a time with an increasing number of job opportunities that require individuals to be capable of not only creating custom content, but of creating custom content that is live with interactive opportunities, it is important that artists become capable of utilizing technologies that allow for this. There are many tools available to artists to create these types of artworks. Fortunately, the principles underlying most of these technologies are transferable. Therefore, it is critical that artists learn at least one of these environments at a deep level. The knowledge and skills developed in one are then transferable to others.
This course will involve engaging classes that involve hands-on work. These will be complimented with in-class lectures on technique, critical listening to ground your work, and discussions of aesthetics as it relates to this type of sonic art. Assessment of students will be conducted through weekly sketches and two larger artworks.
## Objectives & Student Learning Outcomes
Through this course, students are expected to demonstrate an ability to:
- Discuss technical and aesthetic concerns within sonic arts that relate to creating custom art via specific programming environments.
- Employ the Unit Generator paradigm in relation to real-time signal based digital environments.
- Explain an understanding of digital audio signal flow as it relates to a non-DAW based sonic art creative process.
- Create organized code and have an ability to asses organization structures in other's code as it relates to artistic ideas.
- Synthesize creative sonic art works that consider both relevant aesthetics of the medium and the technical demands of working with code.
- Present one significant sonic art work to the public.
Students are expected to bring ideas to explore these techniques and skills. The goals of the projects are not simply about the successful application of the technical processes. Instead, the goal is to integrate these elements to make work that is meaningful.
## Course Format
This course will be offered as an in-person experience. Classes will include lectures on both technical topics and aesthetic considerations; critiques of student work; and lab time for student experimenting.
## Pre-Requisites
Students should have completed MART 120 - Creative Coding I. It is also suggested that students have taken MART 220 Creative Coding II and MART 245 - Introduction to the Language and Practice of Sonic Art and Audio.
## Books and Supplies
There are no required texts that you must purchase for this course. All readings, music, or sound examples will be available to you through web links, the library, or the class Moodle.
### Headphones
You will need to acquire a pair of headphones for work in this class. I would suggest you invest in a good pair, as part of your grade will be based on the technical quality of your work. If you cannot hear issues because you have poor quality headphones, then you are risking poor grades.
You are looking for reference quality headphones. That means headphones that present your audio to you as honest and neutral as possible. A bad mix should sound like a bad mix. Hyped headphones that accentuate bass or high frequencies in flattering ways can hide detail and mix issues.
_A discussion of headphones will occur on the first day of the course._
#### Suggested Headphones
Headphones, like all professional media gear can be cheap or incredibly expensive. With that in mind, you can get good quality headphones that don't break the bank. Here are a few of my suggestions.
**_Highly Suggested_**
- [Sony MDR7506 Professional Large Diaphragm Headphone - $90](https://www.amazon.com/Sony-MDR7506-Professional-Diaphragm-Headphone/dp/B000AJIF4E/ref=sr_1_1?s=musical-instruments&ie=UTF8&qid=1535053810&sr=1-1&keywords=MDR-7506#) - (An industry standard for recording and working with headphones)
- [Sennheiser HD280PRO Headphone - $100](https://www.amazon.com/gp/product/B00IT0IHOY?tag=audiprodtips-20&ie=UTF8&th=1) - (I have had a pair of these since I was an undergrad. They are still my main pair of headphones for work when I need them. They are built to last and sound great.)
**_Other Recommendations_**
- [Samson SR850 Semi-Open-Back Studio Reference Headphones - $34](https://www.amazon.com/Samson-SR850-Professional-Reference-Headphones/dp/B002LBSEQS/ref=as_li_ss_tl?tag=studioheadphone-20&ie=UTF8&redirect=true&ref_=as_li_tl&linkId=29428ce379cfed3cb2be2666574f5db4) - These are the cheapest that will still “get the job done”.
- [AKG K240STUDIO Semi-Open Studio Headphones - $67](https://www.amazon.com/AKG-240-Semi-Open-Studio-Headphones/dp/B0001ARCFA/ref=as_li_ss_tl?tag=studioheadphone-20&ie=UTF8&redirect=true&ref_=as_li_tl&linkId=0f9783b2deabd78b1bcd62dc1b342c05) - These are great headphones. However, they are “semi-open” which will both improve sound quality for mixing and make anyone sitting within 10 feet of you potentially stare in annoyance.
- [Sennheiser HD 202 II Professional Headphones (Black) - $40](https://www.amazon.com/Sennheiser-HD-202-II-Professional/dp/B003LPTAYI/ref=pd_bxgy_23_2?_encoding=UTF8&pd_rd_i=B003LPTAYI&pd_rd_r=2edf0067-a70d-11e8-b9b0-b9c4745829eb&pd_rd_w=34QDu&pd_rd_wg=CK9Nu&pf_rd_i=desktop-dp-sims&pf_rd_m=ATVPDKIKX0DER&pf_rd_p=7ca3846a-7fcf-4568-9727-1bc2d7b4d5e0&pf_rd_r=V1R67GPDR1C7CYABY16N&pf_rd_s=desktop-dp-sims&pf_rd_t=40701&psc=1&refRID=V1R67GPDR1C7CYABY16N)
- [Audio-Technica ATH-M50x Professional Studio Monitor Headphones - $145](https://www.amazon.com/dp/B00HVLUR86/ref=dp_cerb_3)
- There is also a wireless/bluetooth version of these, that additionally includes an optional wired connection. If you want bluetooth headphones, I would recommend these.
- [beyerdynamic DT 770 PRO 32 Ohm Studio Headphone - $179](https://www.amazon.com/dp/B0778DNYPK?aaxitk=HMFdJ5SDf-t20usaXIOB-w&pd_rd_i=B0016MNAAI&pf_rd_m=ATVPDKIKX0DER&pf_rd_p=54dc821a-0937-4e6f-9da9-f8dd5443145d&pf_rd_s=desktop-sx-top-slot&pf_rd_t=301&pf_rd_i=DT770&hsa_cr_id=9048693010101&sb-ci-n=textLink&sb-ci-v=beyerdynamic%2BDT%2B770%2BPRO%2B80%2BOhm%2BStudio%2BHeadphone&th=1)
For more info, the following guide provides good information on the two major types of headphones and suggestions.
- [Best Studio Headphones: The Ultimate Musician’s Guide](https://ehomerecordingstudio.com/best-recording-studio-headphones/)
### Computer
You will need access to a computer capable of running modern audio synthesis and signal processing environments, as well as digital audio workstations (DAWs) and editing software. This computer should also be capable of real-time signal processing through analog inputs and outputs (i.e., using an audio interface or web cam). Please leverage departmental resources whenever necessary.
### Software
For this semester, we will primarily be utilizing [SuperCollider](https://supercollider.github.io) (SC). This tool is chosen because it is open-source, cross-platform compatible, widely used, and incredibly powerful.
> [SuperCollider](https://supercollider.github.io) is a platform for audio synthesis and algorithmic composition, used by musicians, artists, and researchers working with sound. It is free and open source software available for Windows, macOS, and Linux.
>
> SuperCollider features three major components:
>
> **scsynth**, a real-time audio server, forms the core of the platform. It features 400+ unit generators (“UGens”) for analysis, synthesis, and processing. Its granularity allows the fluid combination of many known and unknown audio techniques, moving between additive and subtractive synthesis, FM, granular synthesis, FFT, and physical modeling. You can write your own UGens in C++, and users have already contributed several hundred more to the sc3-plugins repository.
>
> **sclang**, an interpreted programming language. It is focused on sound, but not limited to any specific domain. sclang controls scsynth via Open Sound Control. You can use it for algorithmic composition and sequencing, finding new sound synthesis methods, connecting your app to external hardware including MIDI controllers, network music, writing GUIs and visual displays, or for your daily programming experiments. It has a stock of user-contributed extensions called Quarks.
>
> **scide** is an editor for sclang with an integrated help system.
Additionally, you will need to utilize a DAW from time to time. You are welcome to use any DAW of your choice. _Please speak with the instructor if you have questions about this._
# Course Policies
## Course Evaluation
Student work and progress will be assessed through:
- In-class discussions and critiques
- You are expected to engage with class discussions about technical and artistic issues.
- You are expected to engage with class discussions about outside readings and listenings.
- You are expected to engage in class critique days of the two projects.
- Sketches
- You will be assigned sketches/compositions/exercises to practice the techniques being discussed in class.
- These are critical to your development.
- Projects
- There will be two larger assigned projects throughout the semester that relate to the current topics being discussed. These are the students opportunity to synthesis creative concerns and technical concerns from multiple weeks of content into singular sonic artworks.
- Project Documentation
- Each project will require project documentation, including; a demo video, academic report describing aesthetic and technical success in relation to the larger field, and a written description.
#### Projects
We will have two projects throughout the course that are relevant to concepts, techniques, and creative ideas from recent content. These are the students opportunity to synthesis creative concerns and technical concerns from multiple weeks of content into singular sonic artworks.
Project grades will be based primarily on the student’s ability to:
1. Demonstrate an understanding of the specific characteristics and integrative capabilities of the assigned topic through artistic output, written documentation, and technical achievement.
2. Articulate a clear and concise perspective within the artwork.
3. Present an organized artistic piece, as well as; technical report, file/program structure, and demo video.
4. Demonstrate engagement with an iterative process of ideation → creation → presentation → assessment.
5. Demonstrate creativity beyond the expected technical requirements.
6. Properly and punctually deliver all assignment files.
**Please Note:** All Projects are required for this course. Failure to complete and submit a project will result in a failing grade for the course. There are no exceptions to this rule. Completion of this course requires all projects be completed.
#### Participation
This class will be participatory, and you are expected to participate in discussions and give feedback to other students.
## Grades
#### Final Grades
Grades will be determined according to the following breakdown:
- In-class discussions and critiques: 10%
- Sketches: 50%
- Project 1: 10%
- Project 2: 30%
Letters are assigned according to the following final course percentages:
| Grade | % Range |
|:-----:|:---------:|
| A | `[93-100]`|
| A- | `[90-93)` |
| B+ | `[87-90)` |
| B | `[83-87)` |
| B- | `[80-83)` |
| C+ | `[77-80)` |
| C | `[73-77)` |
| C- | `[70-73)` |
| D | `[60-70)` |
| F | `[0-60)` |
#### Late Work
IMPORTANT: Since projects are experienced as a group in class or through a public presentation, late projects are not permissible and will not be accepted.
Documentation assignments or weekly sketches handed in after the due date and time will have points deducted for lateness. This will be in addition to any points deducted for content. Those that are uploaded late but within one day of the due date will lose 5% for lateness. For those uploaded after that, the number of deducted points will be at the discretion of the professor.
## Attendance
- Attendance will be taken at the beginning of every class
- Critique days are mandatory. No exceptions. No tardiness.
- Contact me in advance if you will not be in class. (email is preferred)
- Unexcused absences will affect your grade.
- One absence is allowed; after that, your final overall grade for the course will drop by 2.5% for each additional absence.
- You are expected to work with colleagues to catch-up on what you missed.
## Course Workload
This course takes time. Some things might be easier than others.
Some week's will be more intense than others. But generally, you should plan to spend 3-9 hours a week on course work outside of class.
In addition, there will be a final presentation of materials, including both a public show and potentially a broadcast on KGBA. These events will both be mandatory and dates will be provided at the start of the semester.
# SVMA, CAM, and University Policies and Information
## School of Visual and Media Arts
Information about the School of Visual and Media Arts (SVMA) is available at:
- [https://svma.umt.edu](https://svma.umt.edu)
Please join SVMA social media to stay informed about events and happenings in our school.
- Instagram: [https://www.instagram.com/umt_svma/](https://www.instagram.com/umt_svma/)
- Facebook: [https://www.facebook.com/UMTsvma](https://www.facebook.com/UMTsvma)
**Student Art Collective** (this is primarily for art students) The collective is a student –organized and student-led group that sponsors art related workshops, events, and the Annual Juried Student Art Show. Look for informational posters. The Director recommends soliciting student participation in art classes.
## Academic Honesty, Plagiarism, and Cheating Policy
Students are expected to adhere to academic conduct policies of the University of Montana as explained in Section V of your [University of Montana Student Conduct Code](https://www.umt.edu/student-affairs/community-standards/default.php): “Academic misconduct is subject to an academic penalty by the course instructor and/or a disciplinary sanction by the University. Academic misconduct is defined as all forms of academic dishonesty, including but not limited to: (1) plagiarism, (2) misconduct during an examination or academic exercise, (3) unauthorized possession of examination or other course materials, (4) tampering with course materials, (5) submitting false information, (6) submitting work previously presented in another course, (7) improperly influencing conduct, (8) substituting, or arranging substitution, for another student during an examination or other academic exercise, (9) facilitating academic dishonesty, and (10) Altering transcripts, grades, examinations, or other academically related documents.”
Dishonesty will not be tolerated in this course. This includes, but is not limited to, cheating on tests, cheating on assignments, fabricating information or citations, having unauthorized possession of examinations, submitting work of another person or work previously used, or tampering with the academic work of other students. Academic misconduct is defined within the Student Conduct Code handbook.
Students who cheat or plagiarize will receive academic sanctions, which may include an “F” grade on the assignment, examination, and/or in the course. Students will also be reported to the Dean of Students for possible further disciplinary action.
#### Using Code or Media Found Elsewhere
It is easy to find code and media (i.e. videos, sounds, images, etc.) online. If you use code or media from elsewhere (which you will at times), I expect you to cite the work and author.
If you use found code, you are expected to comment each line, as to what each line does programmatically. _Do not_ summarize several lines of code from a high level (i.e., TV Guide). I expect you to comment each line on a granular level. In addition, in these cases, I am also looking for significant modification of the code, for you to enact your own ideas and to experiment heavily. Significant modification means beyond variable name and value changes. It is bending these concepts to your idea, especially graphically. It is not a copy and paste job. Also, never more than 40% of your code may be supplied from elsewhere. Period. If you use code from online, whether for inspiration, modification or reference, I expect to see a link in your comments from where you got the code and who wrote it. Otherwise it will be considered as plagiarism, and you will fail the assignment. The code must have a reference, along with URL and be commented out LINE BY LINE.
If you use found media, *YOU* are responsible to ensure it is used according to fair-use guidelines. The pieces you make in this course are intended to be portfolio-quality works. Therefore, you should not utilize found media with restrictive use guidelines or licenses. You can read more about various licenses at;
- [opensource.guide](https://opensource.guide/legal/)
- [choosealicense](https://choosealicense.com)
- [GNU Licenses](https://www.gnu.org/licenses/licenses.en.html)
- [Creative Commons Licenses](https://creativecommons.org/share-your-work/licensing-types-examples/)
- [opensource.org](https://opensource.org/licenses)
For found media, you are also expected to cite the media in your documentation for the project.
## Sensitive Subject Matter & Censorship
This course operates under a no censorship policy, and you should feel free to experiment with challenging topics in your projects. That said - if you submit work with violent or sexually explicit themes, containing hate speech, racial slurs or other sensitive subject matter, I might contact you to request more background information on your choices.
Art scholarship and art practice along with teaching and learning involve a critical exploration of ideas, theories, art-making practices, and art movements that encompass such things as the human body, sexuality, race, gender, religions, and cultures. This course can touch upon any of the above categories with an expectation that students will actively participate in all course assignments, discussions, and tests. Given this information, it is the student’s obligation to determine that the requirements conflict with his or her core beliefs. If the student determines that there is a conflict with his or her beliefs, one of the following actions needs to be taken: 1) drop the class before the last day to drop a course without penalty; 2) meet with the instructor within the first week of classes to determine if an accommodation can be made. (Note, faculty, are not required to grant content accommodations.)
## Be Kind
Be respectful to each other, help each other, and be considerate in your communications with the instructional team. No trolling shared work and ideas. Be constructive with any critical feedback you give.
## Diversity Statement
Your experience in this class is important to me. I welcome individuals of all backgrounds, beliefs, ethnicities, genders, gender identities, gender expressions, races, national origins, religious affiliations, sexual orientations, ages, abilities, and other visible and nonvisible differences. Please know that I will gladly honor your request to address you by an alternate name or gender pronoun. All members of this class are expected to contribute to a welcoming, respectful, and inclusive environment for every other member of this class.
## Student Support Resources
### Disability and Equity Accommodations
The University of Montana assures equal access to instruction through collaboration between students with disabilities, instructors, and the Office for Disability Equity (ODE). If you anticipate or experience barriers based on disability, please contact the ODE at: (406) 243-2243, [<EMAIL>](mailto:<EMAIL>), or visit [www.umt.edu/disability](www.umt.edu/disability) for more information. Retroactive accommodation requests will not be honored, so please, do not delay. As your instructor, I will work with you and the ODE to implement an effective accommodation, and you are welcome to contact me privately if you wish.
### The Writing and Public Speaking Center
The Writing and Public Speaking Center provides one-on-one tutoring to students at all levels and at any time in the writing process. Visit now. Visit often. They're ready when you are. [www.umt.edu/writingcenter](www.umt.edu/writingcenter).
### Mental Health and Wellbeing Policy
The University of Montana is committed to advancing the mental health and wellbeing of its students. If you or someone you know is feeling overwhelmed, depressed, and/or in need of support, services are available. For help, visit https://www.umt.edu/diversity/resources/mental-health.php
## COVID-19 Specific Information
- Mask use is required within the classroom or laboratory.
- NOTE: All CAM buildings are considered active classrooms and laboratories, due to the nature of work we conduct in the arts. Therefore masks are required within all CAM buildings (including the entirety of McGill)
- If you feel sick and/or are exhibiting COVID-19 symptoms, please don’t come to class and contact the Curry Health Center at (406) 243-4330.
- If you are required to isolate or quarantine, you will receive support in the class to ensure continued academic progress.
- Please reach out if you need further accommodations due to a COVID-19 case.
- UM recommends students get the COVID-19 vaccine. Please direct your questions or concerns about vaccines to Curry Health Center.
- Where social distancing (maintaining consistent 6 feet between individuals) is not possible, specific seating arrangements will be used to support contact tracing efforts.
- Class attendance and seating will be recorded to support contact tracing efforts.
- Drinking liquids and eating food is discouraged within the classroom.
- Please note this class is being recorded. Notifying students is a requirement if this is the case.
- Up-to-Date COVID-19 Information from the University of Montana
- UM Coronavirus Website: [https://www.umt.edu/coronavirus](https://www.umt.edu/coronavirus)
- UM COVID-19 Operations Plan: [https://www.umt.edu/coronavirus/campus-covid-plan/default.php](https://www.umt.edu/coronavirus/campus-covid-plan/default.php)
As a final reminder, we (The University Community) strongly encourage you to remain vigilant outside the classroom in mitigating the spread of COVID-19. The only way for this semester to be successful and to maintain minimal interruptions to our educational mission is to ensure the safety and health of all members of our community. Please remember that, and make all decisions and choices during this time with this idea above all others; that the safety and health of our entire community is our most important goal.
#### In Case the Instructor Becomes Sick
If I become sick from COVID-19 during the course of this semester, I will do everything I can to maintain my teaching and mentorship, utilizing the existing modalities established for this semester. However, I will obviously be unable to utilize my university office and will therefore have to make adjustments.
If I become unable to attend weekly class sessions, I will alter the course such that you may continue with your individual projects in an appropriate manner. I will also likely ask that you continue to meet as a cohort, so that you can support each other in your research and artistic pursuits.
## Land Acknowledgement
he Séliš-Ql̓ispé Cultural Committee created the language, _"The University of Montana acknowledges that we are in the aboriginal territories of the Salish and Kalispel people Today, we honor the path they have always shown us in caring for this place for the generations to come."_
## Changes to the Course
I reserve the right to change the intended content of this course throughout the semester. This may be done to adjust for the speed of the class, to better meet educational goals, or to account for changes in technology.
---
# Weekly Breakdown
## Week 1
**Part 1**
_Welcome and course overview_
- Course Overview
- Syllabus
- Discussion of Technologies, Tools, and Supplies
- [SuperCollider](https://supercollider.github.io)
- Headphones
- Critique Days (Mandatory)
- Project 1 - Critique in Class; Friday, October 29th
- Project 2 - Critique in Class; Monday, December 3rd
- Extra Meetings (Mandatory)
- Concert Showing (Project 2) - Friday, December 3rd. From 7pm-9pm
- KGBA Presentation (Virtual Attendance Requested) - Wednesday, December 8th. From 8pm-10pm
- Finals Meeting (Wednesday, December 15th; 8:00AM-10:00AM)
- Class Discussion
**Part 2**
_Listening, Inspiration, and Software Installation_
- Headphone Listening and Evaluation Discussion
- [Spotify List of Suggested Tracks](https://open.spotify.com/user/mmusickm/playlist/6KBJcjjPE2QBem7NVuqVEa?si=T90TQ0MpQiqdeuFcc9HkAg)
- Discussion and Listening to artists that will inspire our semester.
- Install SuperCollider
- Review git & GitHub.com
## Week 2
**Part 1**
_No Class Likely for Musick Baby!_
<!-- **Part 2** -->
## Week 3
**Part 1**
_Installation Revisited, "Hello World", and lang vs. engine_
- Review install of SC
- Discussion of
- SCSynth
- SCLang
- SCIDE
- Start Your Engines (SCSynth) - Booting the Server
- String-based "Hello World"
- `.postln`
- An SC Approach to "Hello World" (aka. your first sine wave)
- `{SinOsc.ar()}.play;`
- Executing code by lines (shift + return)
- Declaring Code Blocks (`( )`)
- Executing Code Blocks (cmd/cntrl + return)
- Comments
- line comments (`//`)
- block comments (`/* */`)
**Part 2**
_Moving beyond static sine waves with modulation_
- Controlling Amplitude
- `mul: `
- BinaryOpUGen
- `SinOsc.ar() * 0.2`
- Using the mouse to change parameters.
- `MouseX.kr` & `MouseY.kr`
- Let's make a [Theremin](https://en.wikipedia.org/wiki/Theremin)
- Introspection with polling
- `.poll`
- `.plot`
- Using `SinOsc.ar` to modulate UGen input arguments
- Two ways of approaching Amplitude Modulation (AM Synthesis)
- Frequency Modulation Synthesis via oscillators
- `mul` and `add`
- Error Messages
- Altering parameters in example code
- What is a "UGen"
- [Unit Generators and Synths - SuperCollider help files](http://doc.sccode.org/Tutorials/UGens-and-Synths.html)
- [Unit generator - Wikipedia](https://en.wikipedia.org/wiki/Unit_generator)
- Mathematical Order of Precedence
- Review Basic Data Types
- Int
- Float
- Char
- String
- Symbol
- Array
Sketch TODO: Use MouseX/Y or Additional SinOsc UGens to play. Make an "interesting" synth that explores the relationships between these UGens. Can you recreate what we have been doing in class on your own? Do you understand what is happening? We will share results at the start of next class.
## Week 4
**Part 1**
_Audio Rate vs. Control Rate, Signal Flow, Variables, and Arguments_
- Audio Rate (`.ar`) vs. Control Rate (`.kr`)
- `.plot(duration:1)`
- Variables in SynthDefs
- `var`
- _"Global"_ Variables
- `a` - `z`
- interpreter variables
- `~var`
- environment variables
- Variable scope in SC
- Arguments in SynthDefs
- `arg`
- using `.set(\argname, value)` to alter running synths
- Signal Flow
- Representing Signal Flow in Code
- Pyramid Structure or Nested Code
- Using Variables (`var`)
- variable reassignment
**Part 2**
_Tour of Basic Deterministic Generator UGens, and Functions_
- [Tour of UGens](http://doc.sccode.org/Guides/Tour_of_UGens.html)
- Tour of Deterministic Generator UGens
- [UGens → Generators → Deterministic | SuperCollider Help](http://doc.sccode.org/Browse.html#UGens%3EGenerators%3EDeterministic)
- Functions
- `{}`
- [04. Functions and Other Functionality | SuperCollider Help](http://doc.sccode.org/Tutorials/Getting-Started/04-Functions-and-Other-Functionality.html)
- [05. Functions and Sound | SuperCollider Help](http://doc.sccode.org/Tutorials/Getting-Started/05-Functions-and-Sound.html)
- [Functions | SuperCollider Help](http://doc.sccode.org/Reference/Functions.html)
- [Function | SuperCollider Help](http://doc.sccode.org/Classes/Function.html)
- Evaluating Functions stored in variables
- `.value()`
- Easy SynthDef via function notation (`{}.play;`)
Sketch TODO: Create a simple synth utilizing additive synthesis, subtractive synthesis, amplitude modulation, frequency modulation, or any other deterministic or stochastic UGens that you can play and change via mouse interaction or argument setting. We will share these at the next class.
## Week 5
**Part 1**
_"In Living Stereo", Signal Arrays, and Output_
- Stereo Expansion
- `SinOsc.ar([400, 440])`
- `sig ! 2`
- `.dup`
- `[sig, sig]`
- Stereo UGens
- `Pan2.ar()`
- Mixing down signal arrays
- `Mix([])`
- The output UGen
- `Out.ar()`
- 0-based language (_including audio output Buses_)
**Part 2**
_Envelopes and Randomness_
- 1-dimensional envelopes
- `Line.kr()` & `XLine.kr()`
- `Decay.ar()`
- Linear Envelope
- `linen.kr()`
- ADR, ADSR, Perc, and Custom Envelopes
- `Env.`
- `EnvGen.kr()`
- Using envelopes beyond amplitude control
- Plotting envelopes w/ `.plot`
- `doneAction: x`
- Looping/Triggering Envelopes
- Random Number generation on the language and server
- Data manipulation
- `.linlin`
- `.linexp`
- `.range`
- `.exprange`
- `.clip`
## Week 6
**Part 1**
_Server-Side Sequencing_
- Clock UGens
- `Impulse`
- `Dust`
- `LFNoise0/1/2`
- Trigger UGens
- `Stepper`
- `Select`
- `Trig1`
- `Latch`
- Envelope Gates
Sketch TODO: Create a short algorithmic work that utilizes envelopes and server-side sequencing/triggering.
## Week 7
**Part 1**
_SynthDefs and Synths_
- `SynthDef`'s
- Loading and storing them
- Playing `Synths`
- Initializing Arguments
- Altering Synths
- Load and Play a SynthDef
- The Synth Tree/Graph
- free-ing synths
**Part 2**
_Language-Side Scheduling and Sequencing_
- Scheduling with `{}.fork` & `t.wait`
- `.do{}` loops
- `.stop`
- `TempoClock()`'s
- `Task({})`
- `Routine({})`
-
**Launch Project 1**
- Create a significant sonic artwork using the skills you have thus far acquired with SuperCollider and in Sonic Programming.
- This artwork may be presented as a live work that you "perform" or a fixed-work that is played back from a sound file or SC itself.
- If you create a fixed-work, please feel free to utilize a DAW to edit, mix, and master your content.
- This does not have to be a worked fully realized within SuperCollider.
- However, all sounds should originate from SC, but may be further edited together and mixed in an external environment.
- These are to be significant pieces that show engagement with the creative process as it relates to working with sonic programming.
- To that end, you should document your creative process, including;
- ideas
- tests
- personal responses
- iteration
- creative goals
- desired artistic outcomes
- Documentation should be completed through a combination of recording, git commits, and personal reflection.
Sketch TODO: Write a short work that encapsulates your synth's as SynthDefs. Then utilize language-side scheduling to launch and alter synths algorithmically.
## Week 8
**Part 1**
_Sound Input and Buses_
- Processing Audio from the Real World
- `SoundIn.ar()`
- Warnings about feedback
- Server Options
- Specifying number of input or output bus channels
- An in-depth discussion of Buses
- Audio Buses
- `a = Bus.audio(s,1)`
- `a.index`
- `Out.ar()`
- `In.ar()`
- `InFeedback.ar()`
- `LocalIn.ar()`
- `LocalOut.ar()`
- Overwriting Buses
- Block Processing Explained
- Control Buses
- `c = Bus.audio(s,1)`
- `c.index`
- `c.set(9)`
- Using Buses as Synth Arguments Maps
- `'Synth__00'.map(\freq, c.index)`
**Part 2**
_Nodes, Groups, Effects, and Synth Order_
- Nodes and the Synth Node Tree
- Order of operation
- specifying node order
- `.tail`
- `.head`
- `.before`
- `.after`
- Using Synths as Effects Processors
- Tour of Delay UGens
- `CombN/L/C`
- `Delay`
- `DelayN`
- [Delay UGens | SuperCollider Help](http://doc.sccode.org/Browse.html#UGens%3EDelays)
- Tour of Filter UGens
- `LPF`
- `RLPF`
- `HPF`
- `RHPF`
- `BPF`
- `BRF`
- `Resonz`
- [Filter UGens | SuperCollider Help](http://doc.sccode.org/Browse.html#UGens%3EFilters)
## Week 9 - Crit Day #1
**_Crit Day #1_**
- Present Project 1 artworks in class.
- These will be critiqued in class with the whole class participating.
- Regardless of whether you work is a live or fixed piece, you should submit a fixed version to the instructor. This should be accompanied with a program/gallery note as well as longer artistic description.
## Week 10
**Part 1**
_Sound Files and Buffers_
- What is a Buffer?
- The various ways the Buffers are used in audio processing environments
- Allocating Buffers
- `b=Buffer.alloc(s, 10*)`
- Freeing Buffers
- `b.free`
- Discussion of the importance of freeing buffers
- Loading Audio Files into Buffers
- Playing Buffers
- Rate
- Direction
- Amplitude
- Playing Back LOOOOOOONG Audio Files
- Recording SC
**Part 2**
_Granular Synthesis_
- Granular Synthesis
- Discussion and Description
- Theoretical Underpinnings
- Playing with Grains
- Grain Rate
- Window Functions
- Precise Timing in SC
Sketch TODO: Create a short sound work that explores the use of sound input or soundfiles along with inter-synth bussing.
## Week 11
**Part 1**
_Patterns & PBind_
- Please Read:
- ["Part II - Patterns" from <NAME>'s _A Gentle Introduction to SuperCollider_](https://ccrma.stanford.edu/~ruviaro/texts/A_Gentle_Introduction_To_SuperCollider.pdf)
- This week is a deep dive into the world of algorithmic composition, as allowed through SuperColliders Pattern capabilities.
- Basic Pattern techniques with PBind
- Effecting and controlling everything with patterns
- Patterns Math
- Patterns in Patterns, effecting patterns.
- Creative Approaches to Algorithmic Driven Art
- **Launch Project 2**
- You are to create a significant sonic artwork that will be presented to the public the night of December 3rd.
- This artwork can be a performance-based work or gallery-based work.
- This is a significant work.
- This work is to be made exclusively within SuperCollider
- NOTE: You may bring other media into SC, but you may not create works that are finished outside of SC as in Project 1.
- This is to be significant pieces that show engagement with the creative process as it relates to working with sonic programming.
- To that end, you should document your creative process, including;
- ideas
- tests
- personal responses
- iteration
- creative goals
- desired artistic outcomes
- Documentation should be completed through a combination of recording, git commits, and personal reflection.
**Part 2**
_Performance Issues with SC & Inter-App Audio Routing_
- Technical considerations for SC when performing or presenting live.
- How to setup SC as a performance environment.
- How to setup SC as an installation engine.
- Inter-Application Audio Routing
Sketch TODO: Create a short artwork utilizing patterns and pattern manipulation
## Week 12
**Part 1**
_Fast Fourier Transform (FFT) Processing_
- Overview of the mathematical concepts behind Fourier transforms.
- Signal Analysis in the Frequency-Domain
- Converting signals between time-domain and frequency-domain
- Frequency-Domain based processing
**Part 2**
_Analysis and Basic Machine Listening_
- How can we use audio signals as control data?
- Amplitude following
- Peak following
- Fundamental Frequency Estimation
- Frequency-Domain Analysis Techniques
{% comment %}
## Week 13
**Part 1**
_Open Sound Control_
- What is the Open Sound Control (OSC) protocol
- OSC and your computer
- OSC between SCSynth and SCLang
- Inter-app communication with OSC
- Computer to Computer communication with OSC
- Using your phone to control SC
- TouchOSC
- Lemur
**Part 2**
_Physical Computing_
- Review of Arduinos, Teensy, etc.
- Communicating between Arduino and SC with Serial connection
- OSC Libraries for Arduino and Teensy
- Using an Arduino as a controller
- Controlling Arduino from SC
{% endcomment %}
## Week 13
**_No Class: Due to Thanksgiving Break_**
_Work on Project 2_
## Week 14 - Public Presentation
**Part 1**
_Public Performance and Presentation_
- During class we will setup the presentation areas and performance space for the evening show.
- For those of you presenting gallery-works, you will be responsible for setting up, cleaning, and preparing the gallery spaces.
- After setup is complete of the spaces themselves, you may install your works and test them.
- For those of you presenting performance/concert works, you will be responsible for setting up, cleaning, and preparing the performance space.
- After setup is complete, we will briefly sound-check each piece.
- Call for the evening presentation will be 5:00pm. Please plan to be to the space by that time.
- Gallery spaces will open at 5:30pm.
- The show will start around 7pm.
- Gallery spaces will remain open for 30 minutes after the shows conclusion.
**Part 2**
_Performance in the Evening_
## Week 15
_Formal Critique and Wrap-up Discussion_
- We will have a formal critique of presentations from last week. Please be prepared with a fixed video/audio-representation of your work.
- We will also discuss the semester, future opportunities, and directions that this work can take you.
|
markdown
|
Tiger can be seen in the popular video wearing a simple white t-shirt with denim and lounging comfortably while waiting for his shoot. He has no idea that he is being recorded and begins humming the song. When he realises he's being recorded, he comes to a halt and asks, "What are you doing?"
He captioned the video as, “Us action heroes waiting for our shots be like."
Heropanti 2 is directed by Ahmad Khan and features Tara Sutaria and Nawazuddin Siddiqui in major roles. The actress recently shared a sunkissed snapshot on social media. She captioned it as, “Don’t blame it on the sunshine⚡️☀️."
Along with Tiger Shroff, Kriti Sanon made her Bollywood debut in the sequel to the film. Both of them are set to reconvene for the film Ganapath, which is set to hit theatres in 2022.
Catch us for latest Bollywood News, New Bollywood Movies update, Box office collection, New Movies Release , Bollywood News Hindi, Entertainment News, Bollywood Live News Today & Upcoming Movies 2024 and stay updated with latest hindi movies only on Bollywood Hungama.
|
english
|
Intel has launched new 10th generation Intel Core desktop processors aimed at bolstering gaming experiences as well as enabling 4K video editing for creative pros.
The desktop processor launches come as more employees are working remote and need to upgrade systems. Intel's launch also comes as the company is in a dogfight with AMD, which has been upping its innovation cadence and powering more systems.
Brandt Guttridge, Intel's director of desktop product marketing, spent most of his time talking about game production and performance, but the chips were tested on Adobe's Premiere suite to roll out enhancements on video editing.
Key points include:
The 10th Gen Intel Core S-series processors have speeds up to 5.3 GHz. The Core i9 Unlocked has 10 cores and 20 threads.
Intel is claiming that its Intel Core i9-10900K is the world's fastest gaming processor.
Unlocked Intel Core processors have added perks for those that overclock including a refreshed Intel Extreme Tuning Utility with graphical enhancements and new features. Brandt noted that creative pros are starting to tune Intel processors for video performance.
The processors include Intel Turbo Boost Max 3.0, which identifies the best performing cores to improve performance. Intel's 10th Gen Core desktop processors feature its two best cores without increasing voltage.
|
english
|
package a
import (
"testing"
"github.com/stretchr/testify/assert" // want `use test assertions from "gotest.tools/v3" instead of "github.com/stretchr/testify" \(see https://pkg.go.dev/gotest.tools/v3/assert\)`
)
func IllegalImport(t *testing.T) {
assert.Equal(t, 1, 1)
}
|
go
|
<reponame>paulkoanui/github-cms-action
{
"action": "converted",
"changes": {
"note": {
"from": "Note converted in Archived"
}
},
"project_card": {
"column_id": 7912870,
"content_url": "https://api.github.com/repos/paulkoanui/github-cms/issues/6"
}
}
|
json
|
//////////////////////////////////////////////////////////////////////
// market_data.go
//////////////////////////////////////////////////////////////////////
package market_data
import (
myResponseCommon "github.com/noknow-hub/pkg-go/bybit/response/v2/common"
)
type LatestInformationResponse struct {
*myResponseCommon.Common
Result []*LatestInformation `json:"result"`
}
type LatestInformation struct {
Symbol string `json:"symbol"`
BidPrice string `json:"bid_price"`
AskPrice string `json:"ask_price"`
LastPrice string `json:"last_price"`
LastTickDirection string `json:"last_tick_direction"`
PrevPrice_24h string `json:"prev_price_24h"`
Price24hPcnt string `json:"price_24h_pcnt"`
HighPrice24h string `json:"high_price_24h"`
LowPrice24h string `json:"low_price_24h"`
PrevPrice1h string `json:"prev_price_1h"`
Price1hPcnt string `json:"price_1h_pcnt"`
MarkPrice string `json:"mark_price"`
IndexPrice string `json:"index_price"`
OpenInterest float64 `json:"open_interest"`
OpenValue string `json:"open_value"`
TotalTurnover string `json:"total_turnover"`
Turnover_24h string `json:"turnover_24h"`
TotalVolume float64 `json:"total_volume"`
Volume24h float64 `json:"volume_24h"`
FundingRate string `json:"funding_rate"`
PredictedFundingRate string `json:"predicted_funding_rate"`
NextFundingTime string `json:"next_funding_time"`
CountdownHour float64 `json:"countdown_hour"`
DeliveryFeeRate string `json:"delivery_fee_rate"`
PredictedDeliveryPrice string `json:"predicted_delivery_price"`
DeliveryTime string `json:"delivery_time"`
}
|
go
|
<reponame>33kk/uso-archive
{
"id": 4014,
"name": "Uwants.com",
"description": "Remove ads on the right panel",
"user": {
"id": 4708,
"name": "hkmikemak",
"email": "redacted",
"paypal_email": null,
"homepage": null,
"about": null,
"license": null
},
"updated": "2007-11-04T22:55:25.000Z",
"weekly_install_count": 0,
"total_install_count": 291,
"rating": null,
"after_screenshot_name": "https://userstyles.org/auto_style_screenshots/4014-after.png?r=1613462834",
"obsoleting_style_id": null,
"obsoleting_style_name": null,
"obsolete": 0,
"admin_delete_reason_id": null,
"obsoletion_message": null,
"screenshots": null,
"license": null,
"created": "2007-11-04T22:55:25.000Z",
"category": "site",
"raw_subcategory": "uwants",
"subcategory": "uwants",
"additional_info": null,
"style_tags": [],
"css": "@namespace url(http://www.w3.org/1999/xhtml);\r\n\r\n@-moz-document domain(\"uwants.com\") {\r\n#uouter {\r\nmargin-left: 0px !important; /* L */\r\nmargin-right: 0px !important; /* R */\r\n}\r\n.utop {\r\nwidth: 100% !important;\r\n}\r\n\r\n.uleft {\r\nfloat: left !important;\r\nwidth: 100% !important;\r\nmargin-right: -1px !important;\r\n}\r\n\r\n.uright {\r\nfloat: right !important;\r\nposition: relative !important;\r\nwidth: 170px !important; /* R */\r\nmargin-right: -171px !important; /* -R-1 */\r\nmargin-left: 2px !important;\r\n}\r\n}",
"discussions": [],
"discussionsCount": 0,
"commentsCount": 0,
"userjs_url": "/styles/userjs/4014/uwants-com.user.js",
"style_settings": []
}
|
json
|
Uttar Pradesh batsman Rinku Singh on Thursday was handed a three-month suspension by the Board of Cricket for Cricket in India for participating in an unauthorized T20 tournament in Abu Dhabi. The ban will come into effect from June 1, 2019.
Rinku has been withdrawn from the India ‘A’ squad set to play a multi-day game against Sri Lanka ‘A’ starting on Friday. Rinku, who played for the Kolkata Knight Riders in the recently-concluded Indian Premier League season, did not seek the BCCI’s permission for participating in the tournament, further violating their rules and regulations.
“As per the BCCI norms, a player registered with the board cannot play in any tournaments abroad without its permission.
The BCCI will not tolerate such violations in the future and strict actions will be taken if a player is found violating the BCCI rules and regulations,” the BCCI said in a statement.
The 21-year-old batsman has featured in 19 first-class and 24 List A games apart from making 47 T20 appearances.
|
english
|
<reponame>Jblew/marinesmud-framework
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.jblew.marinesmud.framework.util;
/**
*
* @author teofil
*/
public class TwoTuple<A, B> {
public final A a;
public final B b;
public TwoTuple(A a, B b) {
this.a = a;
this.b = b;
}
}
|
java
|
Mumbai (Maharashtra) [India], July 5 : Maharashtra Chief Minister Eknath Shinde reached his official residence Varsha Bungalow here on Wednesday evening to chair a meeting with Shiv Sena leaders.
Shinde is expected to discuss the entry of the Ajit Pawar-led NCP faction into the government.
Earlier in the day, both factions of the Nationalist Congress Party held simultaneous meetings, in a test of their strengths.
The NCP led by Sharad Pawar held a meeting of its members at YB Chavan Auditorium in Mumbai while Maharashtra Deputy Chief Minister Ajit Pawar held a separate meeting of NCP MPs, MLAs, MLCs, district heads, and state delegates at Mumbai Education Trust (MET) Bandra.
Sharad Pawar's daughter Supriya Sule, MP and party leaders Anil Deshmukh, Balasaheb Patil, Ashok Pawar, Jayant Patil and Rohit Pawar were among those present.
The crisis in Nationalist Congress Party was triggered by Ajit Pawar switching sides on Sunday and joining the Eknath Shinde-BJP government as Deputy Chief Minister. Eight other NCP MLAs took oath on Sunday with Pawar as ministers.
Sharad Pawar termed the meeting as "historic" while coming down heavily on the rival group led by his nephew saying they had not "followed procedure".
"We weren't taken into confidence by the MLAs who decided to split. Ajit Pawar faction has not followed any procedure. Ajit Pawar should have spoken to me if he had any problems. If he had something on his mind he could have approached me," the NCP chief said.
He also attacked the BJP for joining hands with those it had called "corrupt".
Sharad Pawar told his supporters and NCP workers that they have to keep marching ahead despite the hurdles.
Addressing the gathering of the rival faction at Bandra, Ajit Pawar took a swipe at his uncle urging him to step down and give a chance to the new generation.
"You (Sharad Pawar) give us your blessings. . . The other day, he went to the YB Chavan Memorial. . . I was also there. . . you are 83, aren't you going to stop? . . . Give us your blessings and we will pray that you live a long life," Ajit Pawar said.
|
english
|
<gh_stars>0
# Whack-A-Streamdeck - Whack-A-Mole game for the Elgato Stream Deck
# Author: <NAME> <<EMAIL>>
#
import whackastreamdeck.Deck as Deck
from random import randint
from time import time
from time import sleep
import threading
import os
class MoleGame():
def __init__(this, deck, numMoles=3, minDelay=500, maxDelay=1000, explosionDisplayTime=500, gameTime=60000): # Initial State
this.hill = []
this.deck = deck
this.numMoles = numMoles
this.minDelay = minDelay
this.maxDelay = maxDelay
this.gameTime = gameTime
this.score = 0
this.startTime = -1
this.nextUpdateTime = -1
this.gameOverTime = -1
# Mark where the last mole was whacked, to show an explosion
this.explosions = []
this.explosionUpdateTime = -1
this.explosionDisplayTime = explosionDisplayTime
# Game assets
this.moleImage = Deck.getAsset(deck,"Mole.jpeg")
this.blankImage = Deck.getAsset(deck, "Blank.jpeg")
this.explosionImage = Deck.getAsset(deck, "Explosion.jpeg")
# Process management
this.updateLock = threading.Lock()
this.drawLock = threading.Lock()
def keyCallback(deck, key, state):
this.keyCallback(key,state)
this.deck.set_key_callback(keyCallback)
# Storyboard Management
this.storyboard = "notstarted"
this.redraw()
def tick(this):
this.update()
this.redraw()
if this.storyboard != "gameover":
threading.Timer((randint(this.minDelay, this.maxDelay)/1000.0), this.tick).start()
def randbutton(this):
return randint(0, this.deck.key_count()-1)
def start(this):
# Mole positions are randomized in update()
this.storyboard = "started"
this.nextUpdateTime = -1 # Force initial update
this.startTime = time()
this.gameOverTime = this.startTime+(this.gameTime/1000)
this.tick() # set everything in motion!
def duration(this):
return time()-this.startTime
def update(this):
if this.storyboard != "started":
return
t = time()
# Check if any further updates are required
if t>this.gameOverTime:
this.storyboard = "gameover"
return
#elif t>this.nextUpdateTime:
# this.nextUpdateTime = t+(randint(this.minDelay, this.maxDelay)/1000.0)
#else:
# return
# Populate the mole hill with new moles
this.updateLock.acquire()
nextHill = []
for _ in range(this.numMoles):
nextMole = this.randbutton()
# Force the mole to *look* like it has moved: It can't overlap in the new
# hill, and it should be different from any occupied spot in the old hill.
while nextMole in nextHill or nextMole in this.hill:
nextMole = this.randbutton()
nextHill.append(nextMole)
# Remove any covered explosions from the list
try:
this.explosions.remove(nextMole)
except ValueError:
pass
this.hill = nextHill
this.updateLock.release()
this.redraw()
def redraw(this):
with this.drawLock:
if this.storyboard == "notstarted":
Deck.renderString(this.deck, " PRESS KEY TO START", background="black", color="white")
elif this.storyboard == "gameover":
Deck.renderString(this.deck, "GAME XOVER. SCORE: {}".format(this.score))
else:
for key in range(this.deck.key_count()):
if key in this.hill:
image = this.moleImage
elif key in this.explosions:
image = this.explosionImage
else:
image = this.blankImage
this.deck.set_key_image(key, image)
def removeExplosion(this, key):
this.updateLock.acquire()
try:
this.explosions.remove(key)
except ValueError:
pass
this.updateLock.release()
this.redraw()
def keyCallback(this, key, state):
if not state:
return
if this.storyboard in ("gameover", "quit"):
if key == 7:
this.storyboard = "quit"
deck.reset()
deck.close()
this.redraw()
return
elif this.storyboard == "notstarted":
this.start()
elif key in this.hill:
this.updateLock.acquire()
this.score += 1
# Move the mole that was just whacked
nextMole = this.randbutton()
while nextMole in this.hill:
nextMole = this.randbutton()
this.hill.remove(key)
this.hill.append(nextMole)
# Display an explosion icon for some time
this.explosions.append(key)
this.updateLock.release()
threading.Timer(this.explosionDisplayTime/1000.0, this.removeExplosion, args=(key,)).start()
this.redraw()
def printAndSaveHighScores(score):
print("Score: " + str(game.score))
HIGH_SCORE_FILE = os.path.join(os.path.dirname(__file__), "highscores")
if os.path.exists(HIGH_SCORE_FILE):
with open(HIGH_SCORE_FILE,"r") as highScoreFile:
high_scores = eval(highScoreFile.read())
else:
high_scores = []
high_scores.append(game.score)
high_scores.sort(reverse=True)
high_scores = high_scores[:10] # keep ten scores
print("High Scores:")
print("\n".join([str(s) for s in high_scores]))
with open(HIGH_SCORE_FILE, "w") as highScoreFile:
highScoreFile.write(repr(high_scores))
def run():
deck = Deck.getInitializedDeck(background="green");
game = MoleGame(deck)
print("Good luck!")
while game.storyboard != "quit":
#game.update()
sleep(0.1)
|
python
|
<filename>tree/145 BinaryTreePostorderTraversal.cpp
//
// BinaryTreePostorderTraversal.cpp
// Leetcode
//
// Created by Quinn on 2020/7/26.
// Copyright © 2020 Quinn. All rights reserved.
//
#include "TreeNode.h"
#include <vector>
#include <stack>
using namespace::std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution0
{
public:
vector<int> ans;
vector<int> postorderTraversal(TreeNode *root)
{
dfs(root);
return ans;
}
void dfs(TreeNode *u)
{
if (!u)
return;
dfs(u->left);
dfs(u->right);
ans.push_back(u->val);
}
};
class Solution
{
public:
vector<int> postorderTraversal(TreeNode *root)
{
vector<int> ans;
stack<TreeNode *> stk;
TreeNode *p = root, *last = nullptr;
while (p || !stk.empty())
{
while (p)
{
stk.push(p);
p = p->left;
}
p = stk.top();
if (!p->right || last == p->right)
{
last = p;
ans.push_back(p->val);
stk.pop();
p = nullptr;
}
else
{
p = p->right;
}
}
return ans;
}
};
|
cpp
|
<filename>python/send-to-eventhub.py
import json
import logging
import os
import random
import time
import string
from dotenv import load_dotenv
from azure.eventhub import EventHubProducerClient, EventData
def random_text(n=3):
return ''.join([string.ascii_lowercase[random.randint(0, 25)] for i in range(n)])
if __name__ == "__main__":
load_dotenv()
logger = logging.getLogger("azure")
connection_str = os.environ.get("EHUB_SEND_CONN_STR")
eventhub_name = os.environ.get("EHUB_SEND_NAME")
while True:
client = EventHubProducerClient.from_connection_string(connection_str, eventhub_name=eventhub_name)
event_data_batch = client.create_batch()
try:
terms = random.randint(1,50)
tokens = random.randint(0,5)
for i in range(terms):
message = ' '.join([random_text() for i in range(tokens)])
event_data_batch.add(EventData(message))
except ValueError:
pass
with client:
client.send_batch(event_data_batch)
print("Sent {} messages.".format(len(event_data_batch)))
time_to_sleep = random.randint(0,25)
print("Sleeping for {}".format(time_to_sleep))
time.sleep(time_to_sleep)
|
python
|
With 201 horsepower, sticky tires and an excellent shifter, the Turbo R-Spec is a ton of fun.
The second-generation Hyundai Veloster continues to offer a sporty Turbo model.
Under the hood is a 1.6-liter turbocharged engine with 201 horsepower and 195 pound-feet of torque.
As before, the Veloster has two doors on the passenger side but just one on the driver's side. Weird, right?
This is the Turbo R-Spec, which has grippy Michelin Pilot Sport 4 tires on its 18-inch wheels.
A short-throw shifter from B&M makes the six-speed manual transmission even more satisfying to use.
Along with the sportiness, though, the Veloster Turbo still offers practicality, with 19.9 cubic feet of cargo space.
Compared to the base Veloster, the Turbo has retuned suspension and steering, as well as larger brakes.
The center-exit exhausts and subtle roof spoiler contribute to a sporty appearance.
The R-Spec model also features LED head- and taillights.
Keep clicking or scrolling to see more of the 2019 Hyundai Veloster Turbo R-Spec.
|
english
|
package com.cliffc.aa.node;
import com.cliffc.aa.*;
import com.cliffc.aa.type.*;
import com.cliffc.aa.util.Util;
// Load a named field from a struct. Does it's own nil-check testing. Loaded
// value depends on the struct typing.
public class LoadNode extends Node {
private final String _fld;
private final Parse _bad;
public LoadNode( Node mem, Node adr, String fld, Parse bad ) { this(mem,adr,fld,bad,false,false); }
public LoadNode( Node mem, Node adr, String fld, Parse bad, boolean closure_adr, boolean closure_val ) {
super(OP_LOAD,null,mem,adr);
_fld = fld;
_bad = bad;
// TRUE if either the address or value must be a TFP.
// Address: means loading from a closure.
// Value : means loading a closure.
// Both: this is a linked-list display walk, finding the closure at the proper lexical depth.
// Just address: this is loading a local variable at this closure.
// Neither: this is a normal field load from a non-closure structure.
// Just value: not allowed.
assert (closure_adr || !closure_val); // Just value: not allowed
}
public String xstr() { return "."+_fld; } // Self short name
String str() { return xstr(); } // Inline short name
private Node mem() { return in(1); }
Node adr() { return in(2); }
private Node set_mem(Node a, GVNGCM gvn) { return set_def(1,a,gvn); }
public int find(TypeStruct ts) { return ts.find(_fld); }
@Override public Node ideal(GVNGCM gvn, int level) {
Node mem = mem();
Node adr = adr();
Type tadr = adr._val;
BitsAlias aliases = tadr instanceof TypeMemPtr ? ((TypeMemPtr)tadr)._aliases : null;
// If we can find an exact previous store, fold immediately to the value.
// Do not move Loads "up" past unrelated stores, lest we make memory alive twice.
Node st = find_previous_store(gvn,mem(),adr(),aliases,_fld,true);
if( st!=null ) {
if( st instanceof StoreNode ) return (( StoreNode)st).val();
else return ((NewObjNode)st).get(_fld);
}
// Load can move past a Join if all aliases align.
if( mem instanceof MemJoinNode && aliases != null ) {
Node jmem = ((MemJoinNode)mem).can_bypass(aliases);
if( jmem != null ) {
jmem.xval(gvn._opt_mode);
set_mem(jmem,gvn);
return this;
}
}
// Load can move out of a Call, if the function has no Parm:mem - happens
// for single target calls that do not (have not yet) inlined.
if( mem instanceof MProjNode && mem.in(0) instanceof CallNode )
return set_mem(((CallNode)mem.in(0)).mem(),gvn);
// Load can bypass a New or Store if the address does not depend on the New/St.
if( aliases != null && mem instanceof MrgProjNode ) {
NewNode nnn = ((MrgProjNode)mem).nnn();
// Bypass if aliases do not overlap
if( !aliases.test_recur(nnn._alias) )
return set_mem(mem.in(1),gvn);
// Also bypass if address predates the allocation. Here we just see that
// the address comes from the function Parm, and the New is made in the
// function.
Node adr2 = adr instanceof CastNode ? adr.in(1) : adr;
if( adr2 instanceof ParmNode )
return set_mem(mem.in(1),gvn);
}
// Load from a memory Phi; split through in an effort to sharpen the memory.
// TODO: Only split thru function args if no unknown_callers, and must make a Parm not a Phi
// TODO: Hoist out of loops.
if( mem._op == OP_PHI && mem.in(0)._op != OP_LOOP && adr.in(0) instanceof NewNode ) {
Node lphi = new PhiNode(Type.SCALAR,((PhiNode)mem)._badgc,mem.in(0));
for( int i=1; i<mem._defs._len; i++ )
lphi.add_def(gvn.xform(new LoadNode(mem.in(i),adr,_fld,_bad)));
return lphi;
}
return null;
}
// Find a matching prior Store or NewObj - matching field name and address.
// Returns null if highest available memory does not match name & address.
static Node find_previous_store(GVNGCM gvn, Node mem, Node adr, BitsAlias aliases, String fld, boolean is_load ) {
Type tmem0 = mem._val;
if( !(tmem0 instanceof TypeMem) || aliases==null ) return null;
TypeMem tmem = (TypeMem)tmem0;
// Walk up the memory chain looking for an exact matching Store or New
while(true) {
if( mem instanceof StoreNode ) {
StoreNode st = (StoreNode)mem;
if( Util.eq(st._fld,fld) ) {
if( st.adr()==adr ) return st.err(true)== null ? st : null; // Exact matching store
// Matching field, wrong address. Look for no-overlap in aliases
Type tst = st.adr()._val;
if( !(tst instanceof TypeMemPtr) ) return null; // Store has weird address
BitsAlias st_alias = ((TypeMemPtr)tst)._aliases;
if( aliases.join(st_alias) != BitsAlias.EMPTY )
return null; // Aliases not disjoint, might overlap but wrong address
} // Wrong field name, cannot match
mem = st.mem(); // Advance past
} else if( mem instanceof MProjNode ) {
Node mem0 = mem.in(0);
if( mem0 instanceof CallEpiNode ) { // Bypass an entire function call
mem = _find_previous_store_call(gvn,aliases,tmem,(CallEpiNode)mem0,fld,is_load);
if( mem==null ) return null;
} else if( mem0 instanceof MemSplitNode ) { // Lifting out of a split/join region
mem = ((MemSplitNode)mem0).mem();
} else if( mem0 instanceof CallNode ) { // Lifting out of a Call
mem = ((CallNode)mem0).mem();
} else {
throw com.cliffc.aa.AA.unimpl(); // decide cannot be equal, and advance, or maybe-equal andreturn null
}
} else if( mem instanceof MrgProjNode ) {
MrgProjNode mrg = (MrgProjNode)mem;
NewNode nnn = mrg.nnn();
if( nnn instanceof NewObjNode ) {
int idx = ((NewObjNode)nnn)._ts.find(fld);
if( idx >= 0 && adr instanceof ProjNode && adr.in(0) == nnn ) return nnn; // Direct hit
} // wrong field name or wrong alias, cannot match
if( aliases.test_recur(nnn._alias) ) return null; // Overlapping, but wrong address - dunno, so must fail
mem = mrg.mem(); // Advance past
} else if( mem instanceof MemJoinNode ) {
Node jmem = ((MemJoinNode)mem).can_bypass(aliases);
if( jmem == null ) return null;
mem = jmem;
} else if( mem instanceof PhiNode ||
mem instanceof StartMemNode ||
mem instanceof ConNode) {
return null; // Would have to match on both sides, and Phi the results
} else {
throw com.cliffc.aa.AA.unimpl(); // decide cannot be equal, and advance, or maybe-equal andreturn null
}
}
}
// Can bypass call? Return null if cannot or call.mem if can.
static private Node _find_previous_store_call(GVNGCM gvn, BitsAlias aliases, TypeMem tmem, CallEpiNode cepi, String fld, boolean is_load) {
// TODO: Strengthen this. Global no-esc can bypass, IF during inline/clone
// each clone body updates both aliases everywhere.
if( !is_load ) return null; // For now, Store types NEVER bypass a call.
CallNode call = cepi.call();
if( tmem.fld_is_final(aliases,fld) )
return call.mem(); // Loads from final memory can bypass calls. Stores cannot, store-over-final is in error.
TypeMemPtr escs = call.tesc(call._val);
if( escs._aliases.join(aliases)==BitsAlias.EMPTY )
return call.mem(); // Load from call; if memory is made *in* the call this will fail later on an address mismatch.
return null; // Stuck behind call
}
@Override public Type value(GVNGCM.Mode opt_mode) {
Node adr = adr();
Type tadr = adr._val;
if( !(tadr instanceof TypeMemPtr) ) return tadr.oob();
TypeMemPtr tmp = (TypeMemPtr)tadr;
// Loading from TypeMem - will get a TypeObj out.
Node mem = mem();
Type tmem = mem._val; // Memory
if( !(tmem instanceof TypeMem) ) return tmem.oob(); // Nothing sane
TypeObj tobj = ((TypeMem)tmem).ld(tmp);
// Loading from TypeObj - hoping to get a field out.
if( tobj instanceof TypeStruct ) { // Struct; check for field
TypeStruct ts = (TypeStruct)tobj;
int idx = ts.find(_fld); // Find the named field
if( idx != -1 ) return ts.at(idx); // Field type
// No such field
}
return tobj.oob(); // No loading from e.g. Strings
}
// The only memory required here is what is needed to support the Load
@Override public TypeMem live_use(GVNGCM.Mode opt_mode, Node def ) {
if( def==adr() ) return TypeMem.ALIVE;
Type tmem = mem()._val;
if( !(tmem instanceof TypeMem ) ) return tmem.oob(TypeMem.ALLMEM); // Not a memory?
Type tptr = adr()._val;
if( !(tptr instanceof TypeMemPtr) ) return tptr.oob(TypeMem.ALLMEM); // Not a pointer?
if( tptr.above_center() ) return TypeMem.ANYMEM; // Loaded from nothing
return ((TypeMem)tmem).remove_no_escapes(((TypeMemPtr)tptr)._aliases);
}
@Override public ErrMsg err( boolean fast ) {
Type tadr = adr()._val;
if( tadr==Type.ALL ) return null; // Error already
if( tadr.must_nil() ) return fast ? ErrMsg.FAST : ErrMsg.niladr(_bad,"Struct might be nil when reading",_fld);
if( !(tadr instanceof TypeMemPtr) )
return bad("Unknown",fast); // Not a pointer nor memory, cannot load a field
TypeMemPtr ptr = (TypeMemPtr)tadr;
Type tmem = mem()._val;
if( tmem==Type.ALL ) return null; // An error, reported earlier
if( tmem==Type.ANY ) return null; // An error, reported earlier
TypeObj objs = tmem instanceof TypeMem
? ((TypeMem)tmem).ld(ptr) // General load from memory
: ((TypeObj)tmem);
if( !(objs instanceof TypeStruct) || find((TypeStruct)objs) == -1 )
return bad("Unknown",fast);
return null;
}
private ErrMsg bad( String msg, boolean fast ) {
return fast ? ErrMsg.FAST : ErrMsg.field(_bad,msg,_fld);
}
@Override public int hashCode() { return super.hashCode()+_fld.hashCode(); }
@Override public boolean equals(Object o) {
if( this==o ) return true;
if( !super.equals(o) ) return false;
return (o instanceof LoadNode) && Util.eq(_fld,((LoadNode)o)._fld);
}
}
|
java
|
Writing on my Frontline Club blog, I also post a video interview and photo report with regional blogger Arzu Geybullayeva on our recent visit to an ethnic Azeri village in the regions of the Republic of Georgia.
the POLSKI blog highlights Przemek Wajerowicz's London street photography project: From the Upper Deck.
The Durga Puja is an annual festival that celebrates worship of the Hindu goddess Durga. Bengalis believe that Durga is the daughter of Bengal and during the 5 days of festivities she visits her parental home along with her 4 children and 2 close friends.
Aravanski tells his readers how Muslim holiday Eid al Fitr was celebrated in Kyrgyzstan (with photos).
Ideas R Bulletproof posts some pictures of Durga Puja (Moha Shaptami) celebrations at Dhakeswari Temple in Dhaka, Bangladesh.
Russian photographer Oleg Klimov reposts (RUS, ENG) three graphic and disturbing photos of mental asylum patients in Ulyanovsk region, taken by his colleague Valery Shchekoldin in 1998 for Stern.
Owais Mughal at All Things Pakistan posts pictures of some adventurous rides available in Pakistan during the Eid festivities.
China digital times has a series of photos on oldier parade rehearsal for the 60th anniversary of PRC. After looking at the photos, you can understand the cruel and inhuman story of the grand parade.
Leetlegirl's Big Adventures blog posts some telling pictures of the mass exodus from the mega city Dhaka during the Eid holidays, which answer why the capital of Bangladesh is so quiet and free from traffic jams now.
Flickr user Nigel Durrant — a Jamaican living in Guyana — posts sets of images from two well-known public spaces in Georgetown: Bourda Market and National Park.
Flickr user SOG P posts a series of images documenting a visit to a former sugar factory in Marienburg, Suriname.
Samara photographer Victor Pylyavsky flies a paraglider over the city and the region, taking pictures; his beautiful photos are currently part of an open air exhibit at one of the city's central squares. LJ user drugoi has photographed some of these photos and posted them on his blog (RUS).
My Rustic Bajan Garden does a photographic survey of lizards in her garden and reminds readers why these creatures are useful to humans.
Profy writes that Yandex. ru has launched a service similar to Google Street View: panoramic views of Moscow streets.
Heavy rains killed at least 11 people in Brazil, injured hundreds and made thousand homeless in the past week. Citizen photographers have registered the wreckage across the country.
China: How artistic these buildings are!
MOP forum posted a number of photos on some newly constructed residential buildings in Guangzhou. From a far, one can see some “artistic” white pattern. When getting a closer look, their are all cracks. These buildings have all passed the quality check.
|
english
|
<reponame>threepointone/built-devtools
{"compilerOptions":{"composite":true,"outDir":".","baseUrl":".","rootDir":"../../../../../../front_end/entrypoints/js_app"},"files":["../../../../../../front_end/entrypoints/js_app/JsMain.ts"],"references":[{"path":"../../core/common/bundle-tsconfig.json"},{"path":"../../core/host/bundle-tsconfig.json"},{"path":"../../core/i18n/bundle-tsconfig.json"},{"path":"../../core/sdk/bundle-tsconfig.json"},{"path":"../../generated/protocol-tsconfig.json"},{"path":"../../ui/legacy/components/utils/bundle-tsconfig.json"}]}
|
json
|
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/modules/speech/speech_synthesis.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/modules/speech/speech_synthesis_event.h"
#include "third_party/blink/renderer/platform/speech/platform_speech_synthesis_voice.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
SpeechSynthesis* SpeechSynthesis::Create(ExecutionContext* context) {
return new SpeechSynthesis(context);
}
SpeechSynthesis::SpeechSynthesis(ExecutionContext* context)
: ContextClient(context),
platform_speech_synthesizer_(PlatformSpeechSynthesizer::Create(this)),
is_paused_(false) {}
void SpeechSynthesis::SetPlatformSynthesizer(
PlatformSpeechSynthesizer* synthesizer) {
platform_speech_synthesizer_ = synthesizer;
}
void SpeechSynthesis::VoicesDidChange() {
voice_list_.clear();
if (GetExecutionContext())
DispatchEvent(Event::Create(EventTypeNames::voiceschanged));
}
const HeapVector<Member<SpeechSynthesisVoice>>& SpeechSynthesis::getVoices() {
if (voice_list_.size())
return voice_list_;
// If the voiceList is empty, that's the cue to get the voices from the
// platform again.
const Vector<scoped_refptr<PlatformSpeechSynthesisVoice>>& platform_voices =
platform_speech_synthesizer_->GetVoiceList();
size_t voice_count = platform_voices.size();
for (size_t k = 0; k < voice_count; k++)
voice_list_.push_back(SpeechSynthesisVoice::Create(platform_voices[k]));
return voice_list_;
}
bool SpeechSynthesis::speaking() const {
// If we have a current speech utterance, then that means we're assumed to be
// in a speaking state. This state is independent of whether the utterance
// happens to be paused.
return CurrentSpeechUtterance();
}
bool SpeechSynthesis::pending() const {
// This is true if there are any utterances that have not started.
// That means there will be more than one in the queue.
return utterance_queue_.size() > 1;
}
bool SpeechSynthesis::paused() const {
return is_paused_;
}
void SpeechSynthesis::StartSpeakingImmediately() {
SpeechSynthesisUtterance* utterance = CurrentSpeechUtterance();
DCHECK(utterance);
utterance->SetStartTime(CurrentTimeTicksInSeconds());
is_paused_ = false;
platform_speech_synthesizer_->Speak(utterance->PlatformUtterance());
}
void SpeechSynthesis::speak(SpeechSynthesisUtterance* utterance) {
DCHECK(utterance);
utterance_queue_.push_back(utterance);
// If the queue was empty, speak this immediately.
if (utterance_queue_.size() == 1)
StartSpeakingImmediately();
}
void SpeechSynthesis::cancel() {
// Remove all the items from the utterance queue. The platform
// may still have references to some of these utterances and may
// fire events on them asynchronously.
utterance_queue_.clear();
platform_speech_synthesizer_->Cancel();
}
void SpeechSynthesis::pause() {
if (!is_paused_)
platform_speech_synthesizer_->Pause();
}
void SpeechSynthesis::resume() {
if (!CurrentSpeechUtterance())
return;
platform_speech_synthesizer_->Resume();
}
void SpeechSynthesis::FireEvent(const AtomicString& type,
SpeechSynthesisUtterance* utterance,
unsigned long char_index,
const String& name) {
if (!GetExecutionContext())
return;
double elapsed_time_millis =
(CurrentTimeTicksInSeconds() - utterance->StartTime()) * 1000.0;
utterance->DispatchEvent(SpeechSynthesisEvent::Create(
type, utterance, char_index, elapsed_time_millis, name));
}
void SpeechSynthesis::HandleSpeakingCompleted(
SpeechSynthesisUtterance* utterance,
bool error_occurred) {
DCHECK(utterance);
bool should_start_speaking = false;
// If the utterance that completed was the one we're currently speaking,
// remove it from the queue and start speaking the next one.
if (utterance == CurrentSpeechUtterance()) {
utterance_queue_.pop_front();
should_start_speaking = !!utterance_queue_.size();
}
// Always fire the event, because the platform may have asynchronously
// sent an event on an utterance before it got the message that we
// canceled it, and we should always report to the user what actually
// happened.
FireEvent(error_occurred ? EventTypeNames::error : EventTypeNames::end,
utterance, 0, String());
// Start the next utterance if we just finished one and one was pending.
if (should_start_speaking && !utterance_queue_.IsEmpty())
StartSpeakingImmediately();
}
void SpeechSynthesis::BoundaryEventOccurred(
PlatformSpeechSynthesisUtterance* utterance,
SpeechBoundary boundary,
unsigned char_index) {
DEFINE_STATIC_LOCAL(const String, word_boundary_string, ("word"));
DEFINE_STATIC_LOCAL(const String, sentence_boundary_string, ("sentence"));
switch (boundary) {
case kSpeechWordBoundary:
FireEvent(EventTypeNames::boundary,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()),
char_index, word_boundary_string);
break;
case kSpeechSentenceBoundary:
FireEvent(EventTypeNames::boundary,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()),
char_index, sentence_boundary_string);
break;
default:
NOTREACHED();
}
}
void SpeechSynthesis::DidStartSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
if (utterance->Client())
FireEvent(EventTypeNames::start,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), 0,
String());
}
void SpeechSynthesis::DidPauseSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
is_paused_ = true;
if (utterance->Client())
FireEvent(EventTypeNames::pause,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), 0,
String());
}
void SpeechSynthesis::DidResumeSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
is_paused_ = false;
if (utterance->Client())
FireEvent(EventTypeNames::resume,
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), 0,
String());
}
void SpeechSynthesis::DidFinishSpeaking(
PlatformSpeechSynthesisUtterance* utterance) {
if (utterance->Client())
HandleSpeakingCompleted(
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), false);
}
void SpeechSynthesis::SpeakingErrorOccurred(
PlatformSpeechSynthesisUtterance* utterance) {
if (utterance->Client())
HandleSpeakingCompleted(
static_cast<SpeechSynthesisUtterance*>(utterance->Client()), true);
}
SpeechSynthesisUtterance* SpeechSynthesis::CurrentSpeechUtterance() const {
if (utterance_queue_.IsEmpty())
return nullptr;
return utterance_queue_.front();
}
const AtomicString& SpeechSynthesis::InterfaceName() const {
return EventTargetNames::SpeechSynthesis;
}
void SpeechSynthesis::Trace(blink::Visitor* visitor) {
visitor->Trace(platform_speech_synthesizer_);
visitor->Trace(voice_list_);
visitor->Trace(utterance_queue_);
PlatformSpeechSynthesizerClient::Trace(visitor);
ContextClient::Trace(visitor);
EventTargetWithInlineData::Trace(visitor);
}
} // namespace blink
|
cpp
|
Khali Facebook Par Photo Chhinte song is a Bhojpuri folk song from the Rajai Lekha Kam Aiti released on 2020. Music of Khali Facebook Par Photo Chhinte song is composed by Vivek Byahut. Khali Facebook Par Photo Chhinte was sung by Bittu Deewana. Download Khali Facebook Par Photo Chhinte song from Rajai Lekha Kam Aiti on Raaga.com.
|
english
|
Steketee to Ben Manenti, out Bowled!! Ben Manenti b Steketee 0(6)
Steketee to Harry Nielsen, out Caught by Peirson!! Harry Nielsen c Peirson b Steketee 0(6)
Steketee to Daniel Drew, out Caught&Bowled!! Daniel Drew c and b Steketee 5(30)
|
english
|
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import albumentations
import albumentations.pytorch
import numpy as np
import math
import pandas as pd
import random
import os
import matplotlib
import argparse
import wandb
from EnD import *
from configs import *
from collections import defaultdict
import colour_mnist
import models
from tqdm import tqdm
device = torch.device('cpu')
def num_correct(outputs,labels):
_, preds = torch.max(outputs, dim=1)
correct = preds.eq(labels).sum()
return correct
def train(model, dataloader, criterion, weights, optimizer, scheduler):
num_samples = 0
tot_correct = 0
tot_loss = 0
tot_bce = 0.
tot_abs = 0.
model.train()
for data, labels, color_labels in tqdm(dataloader, leave=False):
data, labels, color_labels = data.to(device), labels.to(device), color_labels.to(device)
optimizer.zero_grad()
with torch.enable_grad():
outputs = model(data)
bce, abs = criterion(outputs, labels, color_labels, weights)
loss = bce+abs
loss.backward()
optimizer.step()
batch_size = data.shape[0]
tot_correct += num_correct(outputs, labels).item()
num_samples += batch_size
tot_loss += loss.item() * batch_size
tot_bce += bce.item() * batch_size
tot_abs += abs.item() * batch_size
if scheduler is not None:
scheduler.step()
avg_accuracy = tot_correct / num_samples
avg_loss = tot_loss / num_samples
return avg_accuracy, avg_loss, tot_bce/num_samples, tot_abs/num_samples
def test(model, dataloader, criterion, weights):
num_samples = 0
tot_correct = 0
tot_loss = 0
model.eval()
for data, labels, color_labels in tqdm(dataloader, leave=False):
data, labels, color_labels = data.to(device), labels.to(device), color_labels.to(device)
with torch.no_grad():
outputs = model(data)
loss = criterion(outputs, labels, color_labels, weights)
batch_size = data.shape[0]
tot_correct += num_correct(outputs, labels).item()
num_samples += batch_size
tot_loss += loss.item() * batch_size
avg_accuracy = tot_correct / num_samples
avg_loss = tot_loss / num_samples
return avg_accuracy, avg_loss
def main(config):
seed = 42
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.manual_seed(seed)
train_loader, valid_loader = colour_mnist.get_biased_mnist_dataloader(
f'{os.path.expanduser("~")}/data',
config.batch_size,
config.rho,
train=True
)
biased_test_loader = colour_mnist.get_biased_mnist_dataloader(
f'{os.path.expanduser("~")}/data',
config.batch_size,
1.0,
train=False
)
unbiased_test_loader = colour_mnist.get_biased_mnist_dataloader(
f'{os.path.expanduser("~")}/data',
config.batch_size,
0.1,
train=False
)
print('Training debiased model')
print('Config:', config)
model = models.simple_convnet()
model = model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=config.lr, weight_decay=config.weight_decay)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1, verbose=True)
hook = Hook(model.avgpool, backward=False)
def ce(outputs, labels, color_labels, weights):
return F.cross_entropy(outputs, labels)
def ce_abs(outputs, labels, color_labels, weights):
loss = ce(outputs, labels, color_labels, weights)
abs = abs_regu(hook, labels, color_labels, config.alpha, config.beta)
return loss, abs
best = defaultdict(float)
for i in range(config.epochs):
train_acc, train_loss, train_bce, train_abs = train(model, train_loader, ce_abs, None, optimizer, scheduler=None)
scheduler.step()
valid_acc, valid_loss = test(model, valid_loader, ce, None)
biased_test_acc, biased_test_loss = test(model, biased_test_loader, ce, None)
unbiased_test_acc, unbiased_test_loss = test(model, unbiased_test_loader, ce, None)
print(f'Epoch {i} - Train acc: {train_acc:.4f}, train_loss: {train_loss:.4f} (bce: {train_bce:.4f} abs: {train_abs:.4f});')
print(f'Valid acc {valid_acc:.4f}, loss: {valid_loss:.4f}')
print(f'Biased test acc: {biased_test_acc:.4f}, loss: {biased_test_loss:.4f}')
print(f'Unbiased test acc: {unbiased_test_acc:.4f}, loss: {unbiased_test_loss:.4f}')
if valid_acc > best['valid_acc']:
best = dict(
valid_acc = valid_acc,
biased_test_acc = biased_test_acc,
unbiased_test_acc = unbiased_test_acc
)
if not config.local:
metrics = {
'train_acc': train_acc,
'train_loss': train_loss,
'train_bce': train_bce,
'train_abs': train_abs,
'valid_acc': valid_acc,
'valid_loss': valid_loss,
'biased_test_acc': biased_test_acc,
'biased_test_loss': biased_test_loss,
'unbiased_test_acc': unbiased_test_acc,
'unbiased_test_loss': unbiased_test_loss,
'best': best
}
wandb.log(metrics)
torch.save({'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'config': config}, os.path.join(wandb.run.dir, 'model.pt'))
if __name__ == '__main__':
if not config.local:
hyperparameters_defaults = dict(
lr=config.lr,
alpha=config.alpha,
beta=config.beta,
weight_decay=config.weight_decay,
batch_size=config.batch_size,
epochs=config.epochs,
rho=config.rho
)
hyperparameters_defaults.update(vars(config))
tags = ['abs']
if config.alpha == 0 and config.beta == 0:
tags = ['baseline']
tags.append(str(config.rho))
wandb.init(
config=hyperparameters_defaults,
project='EnD-cvpr21',
anonymous='allow',
name=f'biased-mnist-rho{str(config.rho)}-{tags[0]}-valid',
tags=tags,
group=tags[0]
)
device = torch.device(config.device)
main(config)
|
python
|
{
"courseCode": "SW5213",
"courseCredit": "4",
"description": "It is estimated that in any given society 3 \u2010 10% of the population has some form of disability. This increases to 15% when the definition of disability includes people who are limited in activity due to chronic conditions. In Singapore a conservative estimate of persons with some form of disability may be anywhere from 120,000 to 400,000 individuals. This would include both a medical perspective as well as a socio\u2010functional perspective which emphasizes the need to address economic, environmental and cultural barriers. This module will use a life span perspective to discuss the impact of disability on the individual and the family. It will also use a systemic, ecological perspective to discuss the management, intervention and delivery of social services to people with disabilities.",
"faculty": "Arts and Social Science",
"title": "Practice with Persons with Disability"
}
|
json
|
<filename>packages/page-bounties/src/helpers/determineUnassignCuratorAction.ts<gh_stars>1-10
// Copyright 2017-2021 @axia-js/app-bounties authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type BN from 'bn.js';
import type { BountyStatus } from '@axia-js/types/interfaces';
import { BN_ZERO } from '@axia-js/util';
import { UserRole, ValidUnassignCuratorAction } from '../types';
export function determineUnassignCuratorAction (roles: UserRole[], status: BountyStatus, blocksUntilUpdate?: BN): ValidUnassignCuratorAction[] {
const actions: ValidUnassignCuratorAction[] = [];
if (status.isCuratorProposed && roles.includes('Member')) {
actions.push('UnassignCurator');
}
if (status.isActive) {
if (roles.includes('Member')) {
actions.push('SlashCuratorMotion');
}
if (roles.includes('User') && blocksUntilUpdate && blocksUntilUpdate.lt(BN_ZERO)) {
actions.push('SlashCuratorAction');
}
}
if (status.isPendingPayout && roles.includes('Member')) {
actions.push('SlashCuratorMotion');
}
return actions;
}
|
typescript
|
Thunder rattled outside, as Emily tossed and turned trying to sleep.
She found it hard to sleep, thinking of her missing pet Twilight. Her tiger-striped cat jumped off her arm and ran straight out the back door. She noticed he had been acting strange lately too. Now, she is worried he might be caught in a heavy downpour.
"Poor Twilight," Emily muttered. "I hope you'll be fine."
Still, sleep wouldn't come, so she decided to head out and look for Twilight. Donning on her jacket, in case it rains, she put on her comfy, reliable sneakers as she grabbed her emergency light from the tool cabinet and headed out in the dark.
"Where will I start looking?" Emily suddenly felt silly for leaving the comfort of her bed. She knew she had to look though, or she wouldn't be able to sleep at all. She was used to having Twilight around all the time. She couldn't bear the thought of something bad happening to her companion of three years.
"Let's do this," Emily told herself and started off.
The wind was blowing harder by every step. She was certain that it would soon rain hard. She had to hurry. Emily decided to follow Twilight's trail through her backyard. That was where she last saw him.
Thankfully, the street was well-lit by lamp posts. Some 100 meters farther down the street, she came by an abandoned tool shed -- at least, that's what it looked like to her. The broken door was slightly ajar. Although crazy, scary thoughts were going around in her head, Emily told herself she would be brave for Twilight.
A sudden flash of lightning illuminated the small shed and Emily thought she saw a glimpse of her beloved cat. Mustering enough courage, she widely opened the door and shone her emergency light inside. She then heard tiny meowing and decided to investigate further.
Lo and behold, there was her Twilight beside a white momma cat and her kittens. There were four -- one white, one Twilight junior, and two mixed patterns.
"Awww, Twilight! You didn't tell me you're a dada cat now!" Emily gushed at her discovery. "Let's take you all home before the rain sets in."
Gathering all the cats and kittens in an old worn box, Emily hastily set out for home. Big drops started falling as soon as she and the cats reached her porch.
"Whew! We made it home safely." Emily was just glad Twilight and his new family were safe at home with her. Tomorrow, she'll make an appointment at the vet and make provisions for her new family members. But tonight, she'll happily fall asleep.
My books are now available:
|
english
|
<reponame>baklai/onmap
const User = require('../models/user.model');
const Profile = require('../models/profile.model');
const Report = require('../models/report.model');
const findOneByLogin = async (login) => {
return User.findOne({ login });
};
const findAll = async () => {
return User.find({});
};
const findOne = async (id) => {
return User.findById(id);
};
const createOne = async (user) => {
const newUser = await User.create(user);
await Profile.setDefaultProfiles(newUser.id);
return newUser;
};
const updateOne = async (user) => {
return User.findByIdAndUpdate(user.id, user);
};
const removeOne = async (id) => {
await Report.deleteMany({ userID: id });
await Profile.deleteMany({ userID: id });
return User.deleteOne({ _id: id });
};
module.exports = {
findOneByLogin,
findAll,
findOne,
createOne,
updateOne,
removeOne
};
|
javascript
|
const key = process.env.NEXT_PUBLIC_PUBLISHABLE_KEY;
export default async function getItemsSearched(name) {
const url = `https://magic-aliexpress1.p.rapidapi.com/api/bestSales/products?page=1&priceMax=20&priceMin=5&sort=EVALUATE_RATE_ASC&searchName=${name}`
return await fetch(url, {
"method": "GET",
"headers": {
"x-rapidapi-host": "magic-aliexpress1.p.rapidapi.com",
"x-rapidapi-key": key
}
}).then(res => res.json())
}
|
javascript
|
Australia is facing devastating bushfires across the nation. In 2009, in response to the Black Saturday bushfires, then-PM Kevin Rudd responded by suspending federal parliament, dispatching the Australian Defence Force to provide assistance, and launched a Royal Commission. We are in a national crisis now. That’s why I’m calling on the Prime Minister to declare a national emergency.
The fires that we have been experiencing across the country in the Spring/early Summer of 2019 are unprecedented in their scale, having a devastating impact on Australian communities especially in Queensland and NSW. Major cities like Sydney are now choking from the concentration of smoke caused by the fires, such that in some areas of Sydney, particle readings of 734 micrograms per cubic meter were recorded - the equivalent of smoking 37 cigarettes. These fires have also had a devastating impact on Australia's unique flora and fauna, including most worryingly, the koala populations on the East Coast of Australia.
It is time for Prime Minister Scott Morrison to declare a national emergency in response to these fires. It is time to commit more resources to emergency fire services across the country. And it is time to dispatch the Australian Defence Force to help combat these fires and help communities in desperate need of assistance.
|
english
|
While RCB thrashed MI by eight wickets on Monday, the find of last season, Tilak Varma, once again showed a lot of promise along with Punjab youngster Nehal Wadhera.
Mumbai Indians head coach Mark Boucher is confident that the youngsters on whom the franchise has been investing for the past few years will stand up and be counted in this edition of the Indian Premier League.
While RCB thrashed MI by eight wickets on Monday, the find of last season, Tilak Varma, once again showed a lot of promise along with Punjab youngster Nehal Wadhera.
Varma cracked an unbeaten 46-ball 84, while Wadehra scored 21 off 13 deliveries.
"The IPL is a massive event and it's going to be a great opportunity for some of our young boys to really show up," Boucher said in a media release issued by MI.
"The way Mumbai Indians have selected their squads over the last few years has been, how you invest in youngsters for the future. It's now time for those youngsters to show up and basically get the opportunities," the former Proteas keeper said.
MI's bowling coach Shane Bond credited the youngsters for helping MI reaching 171 in the opening game.
"Tilak played brilliantly, and so did the other youngsters," he said.
Speaking after his innings, Varma said, "I always back my shots, and I was doing the same thing here. I was asking my partners what could be a good total here and going accordingly. "
(With inputs from PTI)
|
english
|
MSTC LIMITED (A GOVT. OF INDIA UNDERTAKING)
Net),Management Trainee(MT)
Advertisement (English)
Advertisement (Hindi)
(CLICK HERE)
The candidates should have valid email ID & mobile no. which should be kept active till the declaration of result for receiving important notifications issued by the company.
Last date for application will be 15 days from the date of publication of this advertisement in Employment News dated 27.5.2018.
Visually Impaired candidates (who suffer from not less than 40% of disability) may use the services of a Scribe for the examination. Use of scribe shall be permitted if applied while filling in the application. For this purpose, SCRIBE FORM may be downloaded and submitted at the exam venue.
TA Form may be downloaded from Here.
|
english
|
Uriah Hall is no longer a UFC fighter, but at one point in time, 'Prime Time' was regarded as the second-coming of Anderson Silva. He was a flashy striker with a bottomless supply of knockout power and fast-twitch muscle fibers that made him as dangerous a foe as any inside the octagon.
Recently, a fan took to Twitter to compliment Uriah Hall's infamous knockout over Adam Cella. Unfortunately, he took it poorly, which led to a popular MMA page on Twitter attempting to clarify the situation. When that proved unsuccessful, a second reply from the same page drew far more likes than anything Hall said.
The former UFC fighter was ratioed, which typically describes a situation where one tweet draws more likes than the tweet it was originally replying to. This is the case with Uriah Hall, whose initial aggressive reaction earned 163 likes. Meanwhile, the MMA page, called THEARTOFWAR drew 1,182 likes.
After Hall proved resistant to THEARTOFWAR's explanation, receiving only eight likes, the MMA page's response generated 189 likes. The knockout referenced by the MMA fan, who goes by Tuco Salamanca on Twitter, happened in the third episode of The Ultimate Fighter 17.
The former UFC fighter flattened Adam Cella with a devastating spinning hook kick that left his opponent in an unconscious heap for several minutes, even prompting 'Prime Time' to apologize. UFC president Dana White has since branded it as the most vicious knockout he's ever seen on The Ultimate Fighter.
How good was Uriah Hall's run as a UFC fighter?
Uriah Hall retired as a mixed martial artist in 2022. Despite the athletic gifts and striking skills at his disposal, he never reached the heights of a fighter that was once hailed as Anderson Silva's heir apparent. Despite his massively hyped stretch on The Ultimate Fighter, he failed to win in the finale.
Instead, he suffered a split-decision upset loss to Kelvin Gastelum and never recaptured the magic of his initial appearance. Despite his future attempts to face Israel Adesanya, 'Prime Time' never competed for the UFC middleweight title throughout his tenure with the promotion.
The former UFC fighter's career peaked after defeating his idol Anderson Silva via fourth-round TKO and causing Chris Weidman to suffer one of the most graphic leg breaks in MMA history. He subsequently retired from MMA after a two-fight losing streak.
|
english
|
<gh_stars>1-10
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { BasePageComponent } from '../../page/page.component';
@Component({
selector: 'app-http-module',
templateUrl: './http-module.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HttpModuleComponent extends BasePageComponent {
get httpModule() {
return `
@Module({
imports: [HttpModule],
providers: [CatsService],
})
export class CatsModule {}`;
}
get httpService() {
return `
@Injectable()
export class CatsService {
constructor(private readonly httpService: HttpService) {}
findAll(): Observable<AxiosResponse<Cat[]>> {
return this.httpService.get('http://localhost:3000/cats');
}
}`;
}
get httpServiceJs() {
return `
@Injectable()
@Dependencies(HttpService)
export class CatsService {
constructor(httpService) {
this.httpService = httpService;
}
findAll() {
return this.httpService.get('http://localhost:3000/cats');
}
}`;
}
}
|
typescript
|
India is in talks with the United States to seek an exemption on steel and aluminum tariffs that were imposed by former U.S. President Donald Trump, while offering withdrawal of some retaliatory tariffs, three Indian sources told Reuters.
Negotiators in New Delhi and Washington are hoping to reach an agreement during Indian Prime Minister Narendra Modi’s visit to the U.S. later this month, two Indian government officials and one industry source with direct knowledge of the matter said.
India has offered to withdraw retaliatory tariffs on some agricultural goods such as almonds and walnuts in exchange for exemption on steel tariffs, both government sources said.
However, U.S. negotiators were not “flexible”, leading to doubts over a possible exemption on tariffs on steel, one of the sources said.
“We are discussing, (but) they are not very flexible whether there will be any substantial outcome,” the government source said, declining to be identified.
India’s trade ministry, the Office of the U.S. Trade Representative and the U.S. Department of Commerce did not reply to mail seeking comment.
The Indian officials did not want to be named as they were not authorised to speak to media.
“PM (Modi) is visiting and by that time, they (U.S.) want to come up with something good, which looks positive for both sides,” one of the government source added.
India is willing to discuss other possible trade measures that the U.S. officials may propose, the second government source said.
A top executive at a U.S. industry group said he was not aware of “any serious contemplation” on the part of the U.S. government on the tariff issue and said it was unlikely that they would consider such a request.
“I really don’t think the U.S. government would do that, quite frankly,” said Kevin Dempsey, president of the industry trade group American Iron and Steel Institute.
Trump had imposed 25% tariff on steel and 10% on aluminum in 2018, using Section 232 of a 1962 act that allows the president to restrict imports.
In retaliation, India had imposed tariffs on 28 U.S. products, including almonds, apples, and walnuts.
Last December, The World Trade Organization ruled that U.S. tariffs imposed on steel and aluminium imports by Trump contravened global trading rules, a judgment criticised by Washington.
Separately, at a U.S. Congressional Steel Caucus hearing on Wednesday, several steel industry leaders expressed support for keeping the tariffs in place.
|
english
|
// Copyright 2020 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.finos.legend.pure.m3.serialization.runtime.binary.reference;
import org.eclipse.collections.api.map.ImmutableMap;
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.impl.factory.Maps;
import org.finos.legend.pure.m3.serialization.grammar.Parser;
import org.finos.legend.pure.m3.serialization.grammar.ParserLibrary;
import org.finos.legend.pure.m3.serialization.runtime.PureRuntime;
public class ExternalReferenceSerializerLibrary
{
private final ImmutableMap<String, ExternalReferenceSerializer> serializers;
private ExternalReferenceSerializerLibrary(ImmutableMap<String, ExternalReferenceSerializer> serializers)
{
this.serializers = serializers;
}
public ExternalReferenceSerializer getSerializer(String typePath)
{
return this.serializers.get(typePath);
}
public static ExternalReferenceSerializerLibrary newLibrary(Iterable<? extends ExternalReferenceSerializer> serializers)
{
return new ExternalReferenceSerializerLibrary(indexByType(serializers));
}
public static ExternalReferenceSerializerLibrary newLibrary(ParserLibrary parsers)
{
return newLibrary(parsers.getParsers().flatCollect(Parser.GET_REFERENCE_SERIALIZERS));
}
public static ExternalReferenceSerializerLibrary newLibrary(PureRuntime runtime)
{
return newLibrary(runtime.getIncrementalCompiler().getParserLibrary());
}
private static ImmutableMap<String, ExternalReferenceSerializer> indexByType(Iterable<? extends ExternalReferenceSerializer> serializers)
{
MutableMap<String, ExternalReferenceSerializer> serializersByType = Maps.mutable.empty();
for (ExternalReferenceSerializer serializer : serializers)
{
String typePath = serializer.getTypePath();
ExternalReferenceSerializer old = serializersByType.put(typePath, serializer);
if ((old != null) && (old != serializer))
{
throw new RuntimeException("Multiple serializers for " + typePath);
}
}
return serializersByType.toImmutable();
}
}
|
java
|
<filename>query/tests/it/servers/http/clickhouse_handler.rs<gh_stars>0
// Copyright 2022 <NAME>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_base::base::tokio;
use databend_query::servers::http::middleware::HTTPSessionEndpoint;
use databend_query::servers::http::middleware::HTTPSessionMiddleware;
use databend_query::servers::http::v1::clickhouse_router;
use http::Uri;
use poem::error::Result as PoemResult;
use poem::http::Method;
use poem::http::StatusCode;
use poem::web::headers::Authorization;
use poem::Body;
use poem::Endpoint;
use poem::EndpointExt;
use poem::Request;
use poem::Route;
use pretty_assertions::assert_eq;
use crate::tests::SessionManagerBuilder;
macro_rules! assert_error {
($body:expr, $msg:expr$(,)?) => {{
assert!($body.contains($msg), "{}", $body);
}};
}
macro_rules! assert_ok {
($status:expr, $body:expr) => {{
assert_eq!($status, StatusCode::OK, "{}: {}", $status, $body);
}};
}
#[tokio::test]
async fn test_select() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server.get("bad sql").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "sql parser error");
}
{
let (status, body) = server.post("sel", "ect 1").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "sql parser error");
}
{
let (status, body) = server.post("", "bad sql").await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_error!(body, "sql parser error");
}
{
let (status, body) = server.get("").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "");
}
{
let (status, body) = server.get("select 1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "1\n");
}
{
let (status, body) = server.post("", "select 1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "1\n");
}
{
let (status, body) = server.post("select ", "1").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "1\n");
}
{
// basic tsv format
let (status, body) = server
.get(r#"select number, 'a' from numbers(2) order by number"#)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "0\ta\n1\ta\n");
}
Ok(())
}
#[tokio::test]
async fn test_insert_values() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server.post("create table t1(a int, b string)", "").await;
assert_eq!(status, StatusCode::OK);
assert_error!(body, "");
}
{
let (status, body) = server
.post("insert into table t1 values (0, 'a'), (1, 'b')", "")
.await;
assert_eq!(status, StatusCode::OK);
assert_error!(body, "");
}
{
// basic tsv format
let (status, body) = server.get(r#"select * from t1"#).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(&body, "0\ta\n1\tb\n");
}
Ok(())
}
#[tokio::test]
async fn test_insert_format_values() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server.post("create table t1(a int, b string)", "").await;
assert_eq!(status, StatusCode::OK);
assert_error!(body, "");
}
{
let (status, body) = server
.post("insert into table t1 values", "(0, 'a'), (1, 'b')")
.await;
assert_ok!(status, body);
assert_error!(body, "");
}
{
// basic tsv format
let (status, body) = server.get(r#"select * from t1"#).await;
assert_eq!(status, StatusCode::OK, "{} {}", status, body);
assert_eq!(&body, "0\ta\n1\tb\n");
}
Ok(())
}
#[tokio::test]
async fn test_insert_format_ndjson() -> PoemResult<()> {
let server = Server::new();
{
let (status, body) = server
.post("create table t1(a int, b string null)", "")
.await;
assert_ok!(status, body);
}
{
let jsons = vec![r#"{"a": 0, "b": "a"}"#, r#"{"a": 1, "b": "b"}"#];
let body = jsons.join("\n");
let (status, body) = server
.post("insert into table t1 format JSONEachRow", &body)
.await;
assert_ok!(status, body);
}
{
let (status, body) = server.get(r#"select * from t1 order by a"#).await;
assert_ok!(status, body);
assert_eq!(&body, "0\ta\n1\tb\n");
}
{
let jsons = vec![r#"{"a": 2}"#];
let body = jsons.join("\n");
let (status, body) = server
.post("insert into table t1 format JSONEachRow", &body)
.await;
assert_ok!(status, body);
}
{
let (status, body) = server.get(r#"select * from t1 order by a"#).await;
assert_ok!(status, body);
assert_eq!(&body, "0\ta\n1\tb\n2\tNULL\n");
}
{
let jsons = vec![r#"{"b": 0}"#];
let body = jsons.join("\n");
let (status, body) = server
.post("insert into table t1 format JSONEachRow", &body)
.await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
assert_error!(body, "column a");
}
Ok(())
}
struct QueryBuilder {
sql: String,
body: Option<Body>,
}
impl QueryBuilder {
pub fn new(sql: &str) -> Self {
QueryBuilder {
sql: sql.to_string(),
body: None,
}
}
pub fn body(self, body: impl Into<Body>) -> Self {
Self {
body: Some(body.into()),
..self
}
}
pub fn build(self) -> Request {
let uri = url::form_urlencoded::Serializer::new(String::new())
.append_pair("query", &self.sql)
.finish();
let uri = "/?".to_string() + &uri;
let uri = uri.parse::<Uri>().unwrap();
let (method, body) = match self.body {
None => (Method::GET, Body::empty()),
Some(body) => (Method::POST, body),
};
let basic = Authorization::basic("root", "");
Request::builder()
.uri(uri)
.method(method)
.typed_header(basic)
.body(body)
}
}
struct Server {
endpoint: HTTPSessionEndpoint<Route>,
}
impl Server {
pub fn new() -> Self {
let session_manager = SessionManagerBuilder::create().build().unwrap();
let endpoint = Route::new()
.nest("/", clickhouse_router())
.with(HTTPSessionMiddleware { session_manager });
Server { endpoint }
}
pub async fn get_response(&self, req: Request) -> (StatusCode, String) {
let response = self.endpoint.get_response(req).await;
let status = response.status();
let body = response.into_body().into_string().await.unwrap();
(status, body)
}
pub async fn get(&self, sql: &str) -> (StatusCode, String) {
self.get_response(QueryBuilder::new(sql).build()).await
}
pub async fn post(&self, sql: &str, body: &str) -> (StatusCode, String) {
self.get_response(QueryBuilder::new(sql).body(body.to_string()).build())
.await
}
}
|
rust
|
{
"name": "TheBoard",
"version": "0.0.1",
"private": true,
"description": "TheBoard",
"main": "server.express.js",
"author": {
"name": "zaiboot",
"email": "<EMAIL>"
},
"dependencies": {
"express": "^4.14.0",
"mongodb": "^2.2.5"
},
"repository": {
"type": "https",
"url": "https://github.com/zaiboot/nodejs-playground.git"
}
}
|
json
|
India vs Sri Lanka Asia Cup 2023 Final: India's men cricket team is playing Sri Lanka for the Asia Cup finals being held in Colombo. The match was delayed by 40 mins due to rain. Sri Lanka opened to a ‘Mohammad Siraj on fire' who took five overs in just 16 balls!
India's pace bowler Mohammed Siraj claimed six wickets, four in one over to rattle Sri Lanka's batting after a rain-delayed start in the Asia Cup final on Sunday.
Sri Lanka also lost its first wicket , Kusal Perera, to Jasprit Bumrah in the first over itself. Siraj sent back Pathum Nissanka (2) and then Sadeera Samarawickrama (0) and Charith Aslanka (0) but a hat-trick was averted. He then got Dhananjaya de Silva (4) after one ball.
Siraj got his fifth with the wicket of Sri Lankan captain Dasun Shanaka, equalling an ODI record for a bowler's fastest five-wicket haul from his first 16 balls of the match.
Kusal Mendis hit three boundaries before becoming Siraj's sixth wicket.
Sri Lanka skipper Dasun Shanaka won the toss and elected to bat against India in the Asia Cup final here on Sunday. Sri Lanka made one change, bringing in Dushan Hemantha in place of Maheesh Theekshana.
For India, Virat Kohli, Hardik Pandya, Jasprit Bumrah, Mohammed Siraj and Kuldeep Yadav were back in the playing eleven after being rested for one game, while Washington Sundar came in for injured Axar Patel.
Netizens had a blast with Mohammad Siraj's fifer. This is how Twitter reacted to the blast!
“The historical over of Mohammad Siraj.....!!! 4 wickets in a single over."
“No speed challans for #Siraj today." wrote Delhi police on their official X account.
“The GOAT spell. - 4 wickets by Siraj in a single over." wrote another Twitter user.
“Joint fastest in the ODI history.", lauded another user.
“What a start Boom Boom Bumrah and Mohammed Siraj Miyan." praised another Twitter user.
Sri Lanka: Pathum Nissanka, Kusal Perera, Kusal Mendis, Sadeera Samarawickrama, Charith Asalanka, Dhananjaya de Silva, Dasun Shanaka (captain), Dunith Wellalage, Dushan Hemantha, Pramod Madushan, Matheesha Pathirana.
Unlock a world of Benefits! From insightful newsletters to real-time stock tracking, breaking news and a personalized newsfeed – it's all here, just a click away! Login Now!
|
english
|
import { DatePicker as BaseDatePicker } from '@arco-design/web-react';
import { implementRuntimeComponent } from '@sunmao-ui/runtime';
import { css } from '@emotion/css';
import { Type, Static } from '@sinclair/typebox';
import { FALLBACK_METADATA, getComponentProps } from '../sunmao-helper';
import {
DatePickerPropsSpec as BaseDatePickerPropsSpec,
RangePickerPropsSpec,
} from '../generated/types/DatePicker';
import {
DisabledTimeFunc,
DisabledTimeProps,
} from '@arco-design/web-react/es/DatePicker/interface';
const DatePickerPropsSpec = Type.Object(BaseDatePickerPropsSpec);
const DatePickerStateSpec = Type.Object({
visible: Type.Boolean(),
date: Type.Any(),
dateString: Type.Union([Type.Array(Type.String()), Type.String()]),
});
const DatePickerType = {
month: BaseDatePicker.MonthPicker,
year: BaseDatePicker.YearPicker,
week: BaseDatePicker.WeekPicker,
quarter: BaseDatePicker.QuarterPicker,
date: BaseDatePicker,
};
const RangePicker = BaseDatePicker.RangePicker;
const exampleProperties: Static<typeof DatePickerPropsSpec> = {
disabled: false,
placeholder: 'Please Select',
position: 'bl',
dayStartOfWeek: 0,
allowClear: false,
type: 'date',
range: false,
defaultValue: '',
showTime: false,
panelOnly: false,
size: 'default',
disabledTime: {
disabledHours: [0, 1, 2],
disabledMinutes: new Array(30).fill(0).map((e, i) => i),
disabledSeconds: [10],
},
rangePlaceholder: ['Start date', 'End Date'],
disabledRangeTime: {
disabledHours: [
[0, 1, 2],
[7, 9, 10],
],
disabledMinutes: [new Array(30).fill(0).map((e, i) => i), [58, 59]],
disabledSeconds: [[], []],
},
disabledDate: {
disabledType: 'range',
dateRange: ['2022-5-23', '2022-5-26'],
},
rangeDisabled: [false, false],
clearRangeOnReselect: false,
};
export const DatePicker = implementRuntimeComponent({
version: 'arco/v1',
metadata: {
...FALLBACK_METADATA,
name: 'datePicker',
displayName: 'DatePicker',
exampleProperties,
annotations: {
category: 'Display',
},
},
spec: {
properties: DatePickerPropsSpec,
state: DatePickerStateSpec,
methods: {},
slots: {
footer: {
slotProps: Type.Object({}),
},
triggerElement: {
slotProps: Type.Object({}),
},
},
styleSlots: ['content'],
events: ['onChange', 'onClear', 'onVisibleChange'],
},
})(props => {
const {
disabledTime,
disabledRangeTime,
disabledDate,
range,
placeholder,
rangePlaceholder,
rangeDisabled,
type,
panelOnly,
clearRangeOnReselect,
...cProps
} = getComponentProps(props);
const { elementRef, customStyle, slotsElements, callbackMap, mergeState } = props;
const Picker = DatePickerType[type];
return (
<span ref={elementRef} className={css(customStyle?.content)}>
{range ? (
<RangePicker
disabledTime={(date, type) =>
getDisabledRangeTime(date, type, disabledRangeTime!)
}
disabledDate={current => getDisabledDate(current, disabledDate)}
extra={slotsElements.footer}
triggerElement={panelOnly ? null : slotsElements.triggerElement}
mode={type}
placeholder={rangePlaceholder?.length === 0 ? undefined : rangePlaceholder}
clearRangeOnReselect={clearRangeOnReselect}
{...cProps}
disabled={rangeDisabled}
onChange={(dateString, date) => {
mergeState({
date,
dateString,
});
callbackMap?.onChange?.();
}}
onVisibleChange={visible => {
mergeState({ visible });
callbackMap?.onVisibleChange?.();
}}
/>
) : (
<Picker
disabledTime={date => getDisabledTime(date, disabledTime)}
disabledDate={current => getDisabledDate(current, disabledDate)}
extra={slotsElements.footer}
triggerElement={panelOnly ? null : slotsElements.triggerElement}
placeholder={placeholder}
{...cProps}
onChange={(dateString, date) => {
mergeState({
date,
dateString,
});
callbackMap?.onChange?.();
}}
onVisibleChange={visible => {
mergeState({ visible });
callbackMap?.onVisibleChange?.();
}}
/>
)}
</span>
);
});
function getDisabledDate(
date: Parameters<DisabledTimeFunc>[0],
disabledDate: Static<typeof BaseDatePickerPropsSpec.disabledDate>
) {
if (disabledDate.disabledType === 'after') {
return date!.isAfter(disabledDate.date);
}
if (disabledDate.disabledType === 'before') {
return date!.isBefore(disabledDate.date);
}
if (disabledDate.disabledType === 'range') {
if (!disabledDate.dateRange || !Array.isArray(disabledDate.dateRange)) {
return false;
}
for (let i = 0; i < disabledDate.dateRange.length; i++) {
if (date!.isSame(disabledDate.dateRange[i])) {
return true;
}
}
return false;
}
return false;
}
function getDisabledTime(
date: Parameters<DisabledTimeFunc>[0],
range: Static<typeof BaseDatePickerPropsSpec.disabledTime>
): DisabledTimeProps {
const result: DisabledTimeProps = {};
Object.keys(range).forEach(disabledItem => {
if (['disabledHours', 'disabledMinutes', 'disabledSeconds'].includes(disabledItem)) {
const key = disabledItem as keyof typeof range;
result[key] = () => range[key];
}
});
return result;
}
function getDisabledRangeTime(
date: Parameters<DisabledTimeFunc>[0],
type: 'start' | 'end',
range: Static<typeof RangePickerPropsSpec.disabledRangeTime>
): DisabledTimeProps {
const result: DisabledTimeProps = {};
Object.keys(range).forEach(disabledItem => {
if (['disabledHours', 'disabledMinutes', 'disabledSeconds'].includes(disabledItem)) {
const key = disabledItem as keyof typeof range;
const [start, end] = range[key];
result[key] = () => (type === 'start' ? start || [] : end || []);
}
});
return result;
}
|
typescript
|
Minister for Planning and Development Asad Umar said the process of registration of citizens aged sixty-five and above has been started for vaccination against COVID-19.
In a tweet on Monday, he said citizens who wanted to register for the vaccination should SMS their CNIC number to 1166 for registration. He said the vaccination of this age group will start next month.
Last week, Pakistan approved the third COVID-19 vaccine, Russia’s Sputnik-V, for emergency use. It had earlier approved China’s Sinopharm and the one developed by AstraZeneca and Oxford University too.
The Russian vaccine is given in two shots after three weeks. It has a shelf life of six-month at -18 Celsius.
A fourth vaccine candidate has also completed clinical trials. It is developed by CanSino Biologics Inc (CanSinoBIO).
CanSino trials have shown 65.7% efficacy in preventing symptomatic cases. It has a 90.98% success rate in stopping severe cases of the disease in an interim analysis of global trials.
Sultan said its efficacy in the Pakistani subset at preventing symptomatic cases was 74.8%. It was 100% for preventing severe disease.
The efficacy of the CanSino shot is based on an analysis of 30,000 participants and 101 confirmed cases in Pakistan. The minister said, citing an independent data monitoring committee.
Pakistan has recorded more than 550,000 cases of COVID-19 and more than 12,000 deaths. However, it is yet to get any of the 17 million doses it is expected to get through the COVAX initiative.
The country earlier this month launched a vaccination drive with 500,000 doses of Sinopharm donated by longtime ally China to give to frontline healthcare workers as a priority.
Frontline health workers are receiving the first of the shots as a priority. However, officials recently suspended a health official for out-of-turn vaccination of a PML-N Leader’s daughter and son-in-law.
What do you think of this story? Let us know in the comments section below.
|
english
|
Begin typing your search above and press return to search.
Karishma's hattrick meant that Kickstart FC move to top of IWL points table after defeating East Bengal 3-1.
This was Gokulam’s first win in two matches having drawn the first match goalless at home against Sethu FC.
For the first time, the IWL will be played in a double round-robin format on a home-and-away basis.
|
english
|
<reponame>nikita-bykov/jormungandr<filename>testing/jormungandr-testing-utils/src/wallet/mod.rs<gh_stars>0
pub mod account;
pub mod delegation;
pub mod utxo;
use crate::{
stake_pool::StakePool,
testing::{FragmentBuilder, FragmentBuilderError},
};
use chain_impl_mockchain::{
fee::FeeAlgorithm,
key::EitherEd25519SecretKey,
testing::data::{AddressData, AddressDataValue, Wallet as WalletLib},
transaction::{
InputOutputBuilder, Payload, PayloadSlice, TransactionBindingAuthDataPhantom,
TransactionSignDataHash, Witness,
},
value::Value as ValueLib,
};
use jormungandr_lib::{
crypto::{account::Identifier as AccountIdentifier, hash::Hash, key::Identifier},
interfaces::{Address, Initial, Value},
};
use chain_addr::Discrimination;
use chain_crypto::{Ed25519, Signature};
use rand_core::{CryptoRng, RngCore};
use thiserror::Error;
pub use chain_impl_mockchain::{
block::Block,
certificate::{PoolId, SignedCertificate},
chaintypes::ConsensusVersion,
fee::LinearFee,
fragment::Fragment,
header::HeaderId,
milli::Milli,
transaction::{TransactionBindingAuthData, UnspecifiedAccountIdentifier},
};
#[derive(Error, Debug)]
pub enum WalletError {
#[error("couldn't create file")]
IOError(#[from] std::io::Error),
#[error("cannot add input to the transaction")]
CannotAddInput,
#[error("cannot make witness for the transaction")]
CannotMakeWitness,
#[error("transaction error")]
FragmentError(#[from] FragmentBuilderError),
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum Wallet {
Account(account::Wallet),
UTxO(utxo::Wallet),
Delegation(delegation::Wallet),
}
impl Wallet {
pub fn new_account<RNG>(rng: &mut RNG) -> Wallet
where
RNG: CryptoRng + RngCore,
{
Wallet::Account(account::Wallet::generate(rng))
}
pub fn from_existing_account(
signing_key_bech32: &str,
spending_counter: Option<u32>,
) -> Wallet {
Wallet::Account(account::Wallet::from_existing_account(
signing_key_bech32,
spending_counter,
))
}
pub fn new_utxo<RNG>(rng: &mut RNG) -> Wallet
where
RNG: CryptoRng + RngCore,
{
Wallet::UTxO(utxo::Wallet::generate(rng))
}
pub fn new_delegation<RNG>(delegation_identifier: &AccountIdentifier, rng: &mut RNG) -> Wallet
where
RNG: CryptoRng + RngCore,
{
let mut delegation = delegation::Wallet::generate(rng);
delegation.generate_new_signing_key(delegation_identifier.clone());
Wallet::Delegation(delegation)
}
pub fn address(&self) -> Address {
match self {
Wallet::Account(account) => account.address(Discrimination::Test),
Wallet::UTxO(utxo) => utxo.address(Discrimination::Test),
Wallet::Delegation(delegation) => delegation.address(Discrimination::Test),
}
}
pub fn sign_slice(&self, data: &[u8]) -> Signature<TransactionBindingAuthDataPhantom, Ed25519> {
match self {
Wallet::Account(account) => account.signing_key().as_ref().sign_slice(&data),
_ => unimplemented!(),
}
}
/// Temporary method exposing private key
pub fn signing_key_to_string(&self) -> String {
match self {
Wallet::Account(account) => account.signing_key().to_bech32_str(),
Wallet::UTxO(utxo) => utxo.last_signing_key().to_bech32_str(),
Wallet::Delegation(delegation) => delegation.last_signing_key().to_bech32_str(),
}
}
pub fn identifier(&self) -> Identifier<Ed25519> {
match self {
Wallet::Account(account) => Identifier::from(account.identifier().as_ref().clone()),
Wallet::UTxO(utxo) => utxo.identifier(),
Wallet::Delegation(delegation) => delegation.identifier(),
}
}
pub fn delegation_key(&self) -> Identifier<Ed25519> {
match self {
Wallet::Delegation(delegation) => {
Identifier::from(delegation.last_delegation_identifier().as_ref().clone())
}
_ => unimplemented!(),
}
}
pub fn add_input<'a, Extra: Payload>(
&self,
payload: PayloadSlice<'a, Extra>,
iobuilder: &mut InputOutputBuilder,
fees: &LinearFee,
) -> Result<(), FragmentBuilderError>
where
LinearFee: FeeAlgorithm,
{
match self {
Wallet::Account(account) => account.add_input(payload, iobuilder, fees),
Wallet::UTxO(_utxo) => unimplemented!(),
Wallet::Delegation(_delegation) => unimplemented!(),
}
}
pub fn mk_witness(
&self,
block0_hash: &Hash,
signing_data: &TransactionSignDataHash,
) -> Witness {
match self {
Wallet::Account(account) => account.mk_witness(block0_hash, signing_data),
Wallet::UTxO(utxo) => utxo.mk_witness(block0_hash, signing_data),
Wallet::Delegation(delegation) => delegation.mk_witness(block0_hash, signing_data),
}
}
pub fn confirm_transaction(&mut self) {
match self {
Wallet::Account(account) => account.increment_counter(),
_ => unimplemented!(),
}
}
pub fn stake_key(&self) -> Option<UnspecifiedAccountIdentifier> {
match &self {
Wallet::Account(account) => Some(account.stake_key()),
_ => unimplemented!(),
}
}
pub fn delegation_cert_for_block0(&self, pool_id: PoolId) -> Initial {
FragmentBuilder::full_delegation_cert_for_block0(&self, pool_id)
}
pub fn transaction_to(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
address: Address,
value: Value,
) -> Result<Fragment, WalletError> {
FragmentBuilder::new(block0_hash, fees)
.transaction(&self, address, value)
.map_err(WalletError::FragmentError)
}
pub fn issue_pool_retire_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
stake_pool: &StakePool,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).stake_pool_retire(vec![&self], stake_pool))
}
pub fn issue_pool_registration_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
stake_pool: &StakePool,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).stake_pool_registration(&self, stake_pool))
}
pub fn issue_pool_update_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
stake_pool: &StakePool,
update_stake_pool: &StakePool,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).stake_pool_update(
vec![&self],
stake_pool,
update_stake_pool,
))
}
pub fn issue_full_delegation_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
stake_pool: &StakePool,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).delegation(&self, stake_pool))
}
pub fn issue_owner_delegation_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
stake_pool: &StakePool,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).owner_delegation(&self, stake_pool))
}
pub fn issue_split_delegation_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
distribution: Vec<(&StakePool, u8)>,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).delegation_to_many(&self, distribution))
}
pub fn remove_delegation_cert(
&mut self,
block0_hash: &Hash,
fees: &LinearFee,
) -> Result<Fragment, WalletError> {
Ok(FragmentBuilder::new(block0_hash, fees).delegation_remove(&self))
}
}
impl Into<WalletLib> for Wallet {
fn into(self) -> WalletLib {
let address_data = match self {
Wallet::Account(account) => AddressData::new(
account.signing_key().as_ref().clone(),
Some(account.internal_counter()),
account.address(Discrimination::Test).into(),
),
Wallet::UTxO(utxo) => AddressData::new(
EitherEd25519SecretKey::Normal(utxo.last_signing_key().as_ref().clone()),
None,
utxo.address(Discrimination::Test).into(),
),
Wallet::Delegation(delegation) => AddressData::new(
EitherEd25519SecretKey::Normal(delegation.last_signing_key().as_ref().clone()),
None,
delegation.address(Discrimination::Test).into(),
),
};
let address_data_value = AddressDataValue::new(address_data, ValueLib(0));
WalletLib::from_address_data_value(address_data_value)
}
}
|
rust
|
The Competent Authority has approved the proposal for entrusting additional charge of the post of Chairman and Managing Director, Oil & Natural Gas Corporation Limited (ONGC) to Shri A.K. Hazarika, Director (Onshore), ONGC, on ad hoc basis, for a period of three months, with effect from 01.02.2011 or till a regular incumbent is appointed, or until further orders, whichever event occur at the earliest.
|
english
|
Artificial intelligence will change how work is done, companies and their digital transformation efforts and the workforce.
Artificial intelligence will change how work is done, companies and their digital transformation efforts and the workforce.
Gartner’s 2014 Magic Quadrant on IaaS, which ranks the top 15 players in the Infrastructure-as-a-service (IaaS) market, reaffirmed Amazon Web Services' (AWS) dominance in the IaaS space by once again ranking it number one in the 'Leaders' quadrant, reports Krishan Sharma.
Additional deployment support for Microsoft Azure was said to be "actively underway," according to Netflix.
Oracle is set to give an update on its cloud strategy. But it will have a very different take on the future of the cloud than its rivals.
IBM has acquired a bevy of cloud companies and built a Big Blue cloud stack. Here's a look at the moving parts and how they fit together as IBM moves from hardware to the cloud.
Microsoft made substantial headway in its goal to morph from the Windows company to a cloud company over the past decade.
The packaged software market is way past obsolete. In this article, we'll take a look at the cloud-based freemium model and explore why it might actually be a winning solution for struggling PC independent software vendors.
ILM and the cloud has been a set of conflicting techniques that need reconciling. BMC makes the first attempt at tying together the management of local and cloud services.
Microsoft, Google and Apple are all looking to aggregate your health data, launch wearables and crunch your information in the cloud. How much does being an enterprise class cloud provider matter?
SAP Nation, a book chronicling the bloat of the SAP economy, could also apply to other enterprise tech vendors. Does scale truly represent customer interests?
|
english
|
<reponame>xuan-wang/funcat
#!/root/miniconda3/envs/py36/bin/python3
import time
import tushare as ts
import datetime
from funcat import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.types import NVARCHAR, Float, Integer
from wxpusher import WxPusher as wx
uid = ['UID_4yb8qx3oxePh1ZHCvFpVxNGDRAuf',
'UID_6tyjJDIh80gYNw43z6sTkmMhsJWV',
'UID_x1ArbpSoVqdcRr8EHTJYPQzuwUtY',
'UID_x1ArbpSoVqdcRr8EHTJYPQzuwUtY',
'UID_riafQC67rAZFEkCYdR0tNJICZgrw',
'UID_dZkZx0yYMOBiCavWZ5B16jCl8mH1',
'UID_1HaztzY0IMUIXW13HxlbPzIelXuZ',
'UID_05yCFqGgNwzx3QKCLD5Jdkp87fWh',
'UID_lWAVOTvQLh3dfnIRBhM8IuX9n2K3']
start = "20120801"
end = (datetime.datetime.now() + datetime.timedelta(days=0)).strftime('%Y%m%d')
data_backend = funcat_execution_context.get_data_backend()
trading_dates = data_backend.get_trading_dates(start, end)
order_book_id_list = data_backend.get_order_book_id_list()
freq = 0
engine_ts = create_engine('mysql+mysqlconnector://root:@localhost:3306/ts_stock_basic')
conn = engine_ts.connect()
for ts_code in order_book_id_list:
freq = freq + 1
if freq == 100:
time.sleep(61)
freq = 0
pro = ts.pro_api()
df = pro.stk_holdernumber(ts_code=ts_code, start_date="20120101")
dtype = {
"ts_code": NVARCHAR(length=20),
"ann_date": NVARCHAR(length=20),
"end_date": NVARCHAR(length=20),
"holder_num": Integer(),
}
df.to_sql('holdernumber', engine_ts, index=False, if_exists='append', chunksize=5000, dtype=dtype)
conn.execute("create table tmp select * from holdernumber group by ts_code,ann_date,end_date,holder_num")
conn.execute("drop table holdernumber")
conn.execute("alter table tmp rename to holdernumber")
proxy = conn.execute("select count(*) from holdernumber")
text = "更新mysql数据库股东人数成功,共" + str(proxy.fetchall()) + "条目"
wx.send_message(text, uids=uid, token='')
freq = 0
for ts_code in order_book_id_list:
freq = freq + 1
if freq == 10:
time.sleep(61)
freq = 0
pro = ts.pro_api()
df = pro.top10_floatholders(ts_code=ts_code, start_date=start)
dtype = {
"ts_code": NVARCHAR(length=20),
"ann_date": NVARCHAR(length=20),
"end_date": NVARCHAR(length=20),
"holder_name": NVARCHAR(length=64),
"hold_amount": BigInteger(),
}
df.to_sql('top10_floatholders', engine_ts, index=False, if_exists='append', chunksize=5000, dtype=dtype)
conn.execute("create table tmp select * from top10_floatholders group by ts_code,ann_date,end_date,holder_name,hold_amount")
conn.execute("drop table top10_floatholders")
conn.execute("alter table tmp rename to top10_floatholders")
proxy = conn.execute("select count(*) from top10_floatholders")
text = "更新mysql数据库十大流通股东持股成功,共" + str(proxy.fetchall()) + "条目"
wx.send_message(text, uids=uid, token='')
|
python
|
Dhaka: All examinees from 4,769 educational institutions across Bangladesh cleared the Junior School Certificate (JSC) and Junior Dakhil Certificate (JDC) examinations.
Of the institutions, there are 3,042 schools and 1,727 madrasahs. The number of schools with 100 percent pass rate dropped this year by about 500 but seven more madrasahs joined the rank compared to last year, reports the UNB.
Also, no one from 43 educational institutions passed the exams this year. There were 59 institutions with zero percent pass rate last year.
The results of this year’s JSC and JDC examinations were published on Monday with an average pass rate of 85. 83 percent.
|
english
|
{"derivation": "from G1 (\u1f04\u03c7\u03c1\u03b7\u03c3\u03c4\u03bf\u03c2) (as a negative particle) and G5543 (\u1f04\u03c7\u03c1\u03b7\u03c3\u03c4\u03bf\u03c2);", "kjv_def": "unprofitable", "lemma": "\u1f04\u03c7\u03c1\u03b7\u03c3\u03c4\u03bf\u03c2", "frequency": 1, "strongs_def": " inefficient, i.e. (by implication) detrimental", "outline": "<ol><li> useless, unprofitable</li></ol>"}
|
json
|
# 1461. Check If a String Contains All Binary Codes of Size K
# User Accepted:2806
# User Tried:4007
# Total Accepted:2876
# Total Submissions:9725
# Difficulty:Medium
# Given a binary string s and an integer k.
# Return True if any binary code of length k is a substring of s. Otherwise, return False.
# Example 1:
# Input: s = "00110110", k = 2
# Output: true
# Explanation: The binary codes of length 2 are "00", "01", "10" and "11".
# They can be all found as substrings at indicies 0, 1, 3 and 2 respectively.
# Example 2:
# Input: s = "00110", k = 2
# Output: true
# Example 3:
# Input: s = "0110", k = 1
# Output: true
# Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
# Example 4:
# Input: s = "0110", k = 2
# Output: false
# Explanation: The binary code "00" is of length 2 and doesn't exist in the array.
# Example 5:
# Input: s = "0000000001011100", k = 4
# Output: false
# Constraints:
# 1 <= s.length <= 5 * 10^5
# s consists of 0's and 1's only.
# 1 <= k <= 20
class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
for i in range(2**k):
tmp = str(bin(i))[2:]
if len(tmp) < k:
tmp = '0' * (k-len(tmp)) + tmp
if tmp in s:
# print('fuck')
continue
else:
return False
return True
# Redo
rec = set()
tmp = 0
for i in range(len(s)):
tmp = tmp * 2 + int(s[i])
if i >= k:
tmp -= int(s[i-k]) << k
if i >= k-1:
rec.add(tmp)
return len(rec) == (1<<k)
|
python
|
<reponame>33kk/uso-archive
{
"id": 135829,
"info": {
"name": "Facebook Snow",
"description": "Let it snow on Facebook for Christmas or just for some nice winter atmosphere.",
"additionalInfo": null,
"format": "uso",
"category": "facebook",
"createdAt": "2016-11-30T11:42:58.000Z",
"updatedAt": "2016-12-07T13:38:16.000Z",
"license": "CC0-1.0",
"author": {
"id": 375454,
"name": "kfoirksja"
}
},
"stats": {
"installs": {
"total": 144,
"weekly": 0
}
},
"screenshots": {
"main": {
"name": "135829_after.jpeg",
"archived": false
}
},
"discussions": {
"stats": {
"discussionsCount": 0,
"commentsCount": 0
},
"data": []
},
"style": {
"css": "@-moz-document domain(\"facebook.com\") {\r\n/* CSS3 Snow Animation A PEN BY <NAME>*/\r\n/* https://codepen.io/NickyCDK/pen/AIonk */\r\nbody{\tbackground: none;\tfont-family: Androgyne;\tbackground-image: url('http://www.wearewebstars.dk/codepen/img/s1.png'), url('http://www.wearewebstars.dk/codepen/img//s2.png'), url('http://www.wearewebstars.dk/codepen/img//s3.png');\theight: 100%;\tleft: 0;\tposition: absolute;\ttop: 0;\twidth: 100%;\tz-index:1;\t-webkit-animation: snow 10s linear infinite;\t-moz-animation: snow 10s linear infinite;\t-ms-animation: snow 10s linear infinite;\tanimation: snow 10s linear infinite;}\r\n\r\n@keyframes snow {\r\n 0% {background-position: 0px 0px, 0px 0px, 0px 0px;}\r\n 50% {background-position: 500px 500px, 100px 200px, -100px 150px;}\r\n 100% {background-position: 500px 1000px, 200px 400px, -100px 300px;}\r\n}\r\n@-moz-keyframes snow {\r\n 0% {background-position: 0px 0px, 0px 0px, 0px 0px;}\r\n 50% {background-position: 500px 500px, 100px 200px, -100px 150px;}\r\n 100% {background-position: 400px 1000px, 200px 400px, 100px 300px;}\r\n}\r\n@-webkit-keyframes snow {\r\n 0% {background-position: 0px 0px, 0px 0px, 0px 0px;}\r\n 50% {background-position: 500px 500px, 100px 200px, -100px 150px;}\r\n 100% {background-position: 500px 1000px, 200px 400px, -100px 300px;}\r\n}\r\n@-ms-keyframes snow {\r\n 0% {background-position: 0px 0px, 0px 0px, 0px 0px;}\r\n 50% {background-position: 500px 500px, 100px 200px, -100px 150px;}\r\n 100% {background-position: 500px 1000px, 200px 400px, -100px 300px;}\r\n}\t\r\nbody { background-color:#333 !important;}\r\n#contentCol, #leftCol {background:rgba(255,255,255,0.5)}\r\n._4-u8 {background-color: rgba(255, 255, 255, 0.8);}\r\n.fbIndex .gradient {background: rgba(255, 255, 255, 0.8);}\r\n#pageFooter{background: rgba(255, 255, 255, 0.5);}\r\n._50dz, ._50dz div{background: none !important;}\r\n._50dz div.pvl {background: rgba(255, 255, 255, 0.8) !important;}\r\n}"
}
}
|
json
|
<gh_stars>10-100
{
"name": "node-firefox-forward-ports",
"version": "1.0.0",
"description": "Forward local ports to remote debugging interfaces on connected Firefox OS devices",
"main": "index.js",
"dependencies": {
"adbkit": "^2.1.6",
"es6-promise": "^2.0.1",
"portfinder": "^0.4.0"
},
"devDependencies": {
"gulp": "^3.8.10",
"mockery": "^1.4.0",
"node-firefox-build-tools": "^0.1.0",
"nodemock": "^0.3.4"
},
"scripts": {
"gulp": "gulp",
"test": "gulp test"
},
"repository": {
"type": "git",
"url": "https://github.com/mozilla/node-firefox-forward-ports.git"
},
"keywords": [
"firefox",
"developer tools",
"b2g",
"firefox os",
"firefoxos",
"fxos",
"ports"
],
"author": {
"name": "Mozilla",
"url": "https://mozilla.org/"
},
"contributors": [
{
"name": "<NAME>",
"email": "<EMAIL>",
"url": "http://lmorchard.com"
}
],
"license": "Apache 2.0",
"bugs": {
"url": "https://github.com/mozilla/node-firefox-forward-ports/issues"
},
"homepage": "https://github.com/mozilla/node-firefox-forward-ports",
"gitHead": "d91f23606909e9a84334a668374ee8560dbfcf46",
"_id": "node-firefox-forward-ports@1.0.0",
"_shasum": "3999dd188b739dfaff009252e02672d72085d3bb",
"_from": "node-firefox-forward-ports@",
"_npmVersion": "2.1.9",
"_nodeVersion": "0.10.33",
"_npmUser": {
"name": "tofumatt",
"email": "<EMAIL>"
},
"maintainers": [
{
"name": "tofumatt",
"email": "<EMAIL>"
}
],
"dist": {
"shasum": "3999dd188b739dfaff009252e02672d72085d3bb",
"tarball": "http://registry.npmjs.org/node-firefox-forward-ports/-/node-firefox-forward-ports-1.0.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/node-firefox-forward-ports/-/node-firefox-forward-ports-1.0.0.tgz"
}
|
json
|
#include "music.h"
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
Node n;
int count{};
int choice;
char yes;
int const size = 3;
int i = 0;
music_data s;
fstream data("music.txt", ios::out);
ifstream take("music.txt");
take >> count;
do
{
cout << endl << " " << "=====MENU=====" << endl;
cout << endl << " " << "1.To Enter the data in to the File. " << endl;
cout << endl << " " << "2.To display all of the data." << endl;
cout << endl << " " << "Enter the choice: ";
cin >> choice;
switch (choice)
{
case 1:
do
{
cout << endl << " " << "Enter the name of the song: ";
cin.ignore();
getline(cin, s.name);
cout << endl << " " << "Enter the name of movie: ";
cin.ignore();
getline(cin, s.movie);
cout << endl << " " << "Enter the name of the Singer: ";
cin.ignore();
getline(cin, s.singer);
data.write(reinterpret_cast<char*>(&s), sizeof(s));
cout << endl << " " << "Do you like to store the data again: ";
cin >> yes;
} while (yes == 'Y' && 1 < 3);
for (int i = 0; i < count; i++)
{
take >> n.array[i];
}
break;
default:
break;
}
} while (choice!=3);
system("pause");
return 0;
}
|
cpp
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.